Skip to content
Programmingoneonone
Programmingoneonone

Learn everything about programming

  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

Learn everything about programming

HackerRank Separate the Numbers solution

YASH PAL, 19 May 202530 November 2025

HackerRank Separate the Numbers solution – In this HackerRank Separate the Numbers problem solution, we need to perform queries where each query consists of some integer string.

For each query, print whether or not the string is beautiful on a new line. If it is beautiful, print YES x, where x is the first number of the increasing sequence.

If there are multiple such values of x, choose the smallest. Otherwise, print NO.

Hackerrank separate the numbers problem solution
Separate the numbers

Problem solution in Python

#!/bin/python3

import sys
import math

def generator(first,length):
    length = int(length)
    first = int(first)
    temp = first + 1
    s = str(first)
    s+=str(temp)
    for i in range(length):
        if(len(s) == int(length)):
            return s
        temp += 1
        s += str(temp)
        
q = int(input().strip())
for a0 in range(q):
    s = input().strip()
    for i in range(1,round(len(s)/2)+2):
        t = generator(s[:i],len(s))
        if t == s:
            print("YES" + " " + str(s[:i]))
            break
        elif (i >= (round(len(s)/2))):
            print("NO")
            break

Problem Solution in Java

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'separateNumbers' function below.
     *
     * The function accepts STRING s as parameter.
     */

    public static void separateNumbers(String s) {
        if(s==null || s.isEmpty()) return;

        for (int i = 1; i <= s.length()/2; i++) {
            String possibleStringWithStartingNumber = s.substring(0,i);
            Long startingNumber = Long.parseLong(possibleStringWithStartingNumber);
            // System.out.println("possible string with starting number = " + possibleStringWithStartingNumber);

            for (int j = i; j < s.length() && possibleStringWithStartingNumber.length()<s.length(); j+=i) {
                startingNumber++;
                possibleStringWithStartingNumber = possibleStringWithStartingNumber + startingNumber;
            }
            // System.out.println("possible string with starting number result = " + possibleStringWithStartingNumber);

            if(s.equals(possibleStringWithStartingNumber)) {
                System.out.println("YES " + s.substring(0,i));
                return;
            }
        }

        System.out.println("NO");    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));

        int q = Integer.parseInt(bufferedReader.readLine().trim());

        IntStream.range(0, q).forEach(qItr -> {
            try {
                String s = bufferedReader.readLine();

                Result.separateNumbers(s);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
    }
}

Problem solution in C++

#include <bits/stdc++.h>

using namespace std;

long long getValue(string s, int start, int len)
{
	long long multiplier = 1;
	long long result = 0;
	if (start + len > s.length() || s[start] == 48)
	{
		return -1;
	}
	for (int i = start + len -1 ; i >=start ;i--)
	{
	result += ((char)s[i] - 48)*multiplier;
		multiplier *= 10;
	}
	return result;
}

long long solveSub(string s, int len)
{
	long long firstValue = getValue(s, 0, len);
	if (firstValue == -1)
	{
		return -1;
	}
	int currentPos = len;
	int lastLen = len;
	long long lastValue = firstValue;
	
	while (true)
	{
		long long val = getValue(s, currentPos, lastLen);
		if (val != -1 && val == lastValue + 1)
		{
			// if finished
			if (currentPos + lastLen == s.length())
			{
				return firstValue;
			}

			// go further
			currentPos += lastLen;
			lastValue = val;
			continue;
		}

		val = getValue(s, currentPos, lastLen + 1);
		if (val != -1 && val == lastValue + 1)
		{
			// if finished
			if (currentPos + lastLen +1 == s.length())
			{
				return firstValue;
			}

			// go further			
			lastLen++;
			currentPos += lastLen;
			lastValue = val;
			continue;
		}

		return -1;
	}
}

void solve(string s)
{
    for (int len = 1; len <= s.length()/2; len++)
    {
        long long val = solveSub(s, len);
        if (val != -1)
        {
            cout << "YES " << val << endl;
            return;
        }				
    }
	cout << "NO" <<  endl;
}

int main() {
	int q;
	cin >> q;
	for (int a0 = 0; a0 < q; a0++) {
		string s;
		cin >> s;
		solve(s);
	}
	return 0;
}

Problem Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

long myatol(char *s, int i, int j)
{
    long v = 0;
    int k;
    for (k = i; k < j; k++)
        v = v * 10 + (s[k] - '0');
    return v;
}
int main(){
    int q, a0; 
    scanf("%d",&q);
    for (a0 = 0; a0 < q; a0++) {
        int i, j, len, yes = 0;
        char buf[32];
        char* s = (char *)malloc(512000 * sizeof(char));
        long u, v;
        scanf("%s",s);
        len = strlen(s);
        for (i = 1; i <= len/2; i++) {
            int cmp = 0;
            u = myatol(s, 0, i);
            v = u;
            j = i;
            while (j < len) {
                int len1;
                sprintf(buf, "%lu", v+1);
                len1 = strlen(buf);
                cmp = strncmp(buf, &s[j], len1);
                if (cmp) break;
                v = v+1;
                j += len1;
            }
            if (0 == cmp) {
                yes = 1;
                break;
            }
        }
        if (yes)
            printf("YES %ld\n", u);
        else
            printf("NO\n");
            
        free(s);
    }
    return 0;
}

Problem solution in JavaScript

process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

const nextNumber = s => {
    let i = s.length - 1
    
    if ( i > 0 && s.charAt(0) === '0' ) return "NaN"
    
    while(s.charAt(i) == '9' && i > 0) i--
    
    return s.substr(0,i) + (parseInt(s.substr(i,1))+1) + "0".repeat(s.length-1-i)
}


function separateNumbers(s) {
  
    if ( s.length > 32 ) return console.log("NO")
    
    for(let i = 1; (s.length/i) >= 2 && i <= 16; i++){
        let isBeautiful = true
        let length = i
        
        for(let j = 0 ; j < s.length;){
            let current = s.substr(j,length)
            let next = nextNumber(current)
            
            if ( s.length == (j+length) ) break
            else if ( s.length < j + next.length || s.substr(j+length,next.length) !== next ){
                isBeautiful = false
                break
            }
            
            j += current.length
            length = next.length
        }
        
        if (isBeautiful) return console.log('YES ' + s.substr(0,i))
    }
    
    return console.log('NO')
}

function main() {
    var q = parseInt(readLine());
    for(var a0 = 0; a0 < q; a0++){
        var s = readLine();
        separateNumbers(s);
    }

}
Follow my blog with Bloglovin
Algorithms AlgorithmsHackerRank

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes