HackerRank Separate the Numbers Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Separate the Numbers Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank Separate the Numbers Solution
HackerRank Separate the Numbers Solution

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Separate the Numbers Solution

Task

A numeric string, s, is beautiful if it can be split into a sequence of two or more positive integers, a[1], a[2], . . . , a[n], satisfying the following conditions:

  1. a[i] – a[i – 1] = 1 for any 1 < i <= n (i.e., each element in the sequence is 1 more than the previous element).
  2. No a[i] contains a leading zero. For example, we can split s = 10203 into the sequence {1, 02, 03}, but it is not beautiful because 02 and 03 have leading zeroes.
  3. The contents of the sequence cannot be rearranged. For example, we can split s = 312 into the sequence {3, 1, 2}, but it is not beautiful because it breaks our first constraint (i.e.1 – 3 != 1).

The diagram below depicts some beautiful strings:

image

Perform q queries where each query consists of some integer string s. 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.

Function Description

Complete the separateNumbers function in the editor below.

separateNumbers has the following parameter:

  • s: an integer value represented as a string

Prints
– string: Print a string as described above. Return nothing.

Input Format

The first line contains an integer q, the number of strings to evaluate.
Each of the next q lines contains an integer string s to query.

Constraints

  • 1 <= q <= 10
  • 1 <= |s| <= 32
  • s[i] ∈ [0 – 9]

Sample Input 0

7
1234
91011
99100
101103
010203
13
1

Sample Output 0

YES 1
YES 9
YES 99
NO
NO
NO
NO

Explanation 0

The first three numbers are beautiful (see the diagram above). The remaining numbers are not beautiful:

  • For s = 101103, all possible splits violate the first and/or second conditions.
  • For s = 010203, it starts with a zero so all possible splits violate the second condition.
  • For s = 13, the only possible split is {1, 3}, which violates the first condition.
  • For s = 1, there are no possible splits because s only has one digit.

Sample Input 1

4
99910001001
7891011
9899100
999100010001

Sample Output 1

YES 999
YES 7
YES 98
NO

HackerRank Separate the Numbers Solution

Separate the Numbers Solution in C

#include <stdio.h>
#include <string.h>
typedef unsigned long long int Long;
char s[33];
int q;
Long x;
int isZeroLead(int i) { return s[i] == '0'; }
Long read(int i, int sz) {
    char *pt = s + i;
    Long ans = 0;
    while(sz-- && *pt) {
        ans = ans*10 + (*pt - '0');
        pt++;
    }
    return ans;
}
int digs(Long x) {
    int ll = 0;
    while(x) {
        ll++;
        x /= 10;
    }
    return ll;
}
int check(Long fst, int len) {
    Long last = fst, curr;
    int lsz = digs(fst);
    for(int i = lsz; i < len; i += lsz) {
        if(isZeroLead(i)) return 0;
        if(digs(last + 1) != digs(last)) { lsz++; }
        
        curr = read(i, lsz);
        if(curr - last != 1) return 0;
        last = curr;
    }
    
    return 1;
}
int main() {
    scanf("%d",&q);
    while(q--) {
        scanf("%s", s);
        Long x = -1, fst;
        for(int i = 1, len = strlen(s); i <= (len>>1); i++) {
            fst = read(0, i);
            if(check(fst, len)) {
                x = fst;
                break;
            }
        }
        
        if(x == -1) puts("NO");
        else printf("YES %lld\n", x);
    }
    
    return 0;
}

Separate the Numbers Solution in Cpp

#include <bits/stdc++.h>
#define modx 1000000009
#define ll long long
#define pb push_back
#define mp make_pair
#define PI 3.14159265359
using namespace std;
long long int gcd( long long int a , long long int b )
{
    return b == 0 ? a : gcd( b , a%b );
}
#define N 34
string str ;
int main( )
{
    int q ;
    cin >> q ;
    while( q-- ) {
        cin >> str ;
        if( str[ 0 ] == '0' ) {
            cout << "NO" << endl ;
            continue ;
        }
        bool flag = false ;
        int n = str.length() ;
        long long cur_val = 0 ;
        for( int i = 0 ; i < n - 1 ; i++ ) {
              cur_val = cur_val * 10 + str[ i ] - '0' ;
              int j = i + 1 ;
              long long exp_val = cur_val + 1 , new_val = 0 ;
              while( j < n ) {
                    if( new_val == 0 && str[ j ] == '0' ) {
                        new_val = 1 ;
                        break ;
                    }
                  
                    new_val = new_val * 10 + str[ j ] - '0' ;
                    if( new_val == exp_val ) {
                          exp_val++ ;
                          new_val = 0 ;
                    }
                    j++ ;
              }
              if( new_val == 0 ) {
                  cout << "YES" << " " << cur_val << endl ;
                  flag = true ;
                  break ;
              }
        }
        if( flag == false ) cout << "NO" << endl ;
    }
    return 0 ;
}

Separate the Numbers Solution in Java

import java.io.*;
import java.util.StringTokenizer;
/**
 * @author Aydar Gizatullin a.k.a. lightning95, [email protected]
 *         Created on 17.02.17.
 */
public class Main {
    private void solve() {
        int n = rw.nextInt();
        main:
        for (int i = 0; i < n; ++i) {
            String s = rw.next();
            if (s.startsWith("0") || s.length() == 1) {
                rw.println("NO");
                continue;
            }
            long x, cur;
            cy:
            for (int j = 1; j <= s.length() / 2; ++j) {
                x = Long.parseLong(s.substring(0, j));
                cur = x + 1;
                int c = j;
                while (c < s.length()) {
                    String p = String.valueOf(cur);
                    cur += 1;
                    if (s.startsWith(p, c)) {
                        c += p.length();
                    } else {
                        continue cy;
                    }
                }
                rw.println("YES" + " " + x);
                continue main;
            }
            rw.println("NO");
        }
    }
    private RW rw;
    private String FILE_NAME = "file";
    public static void main(String[] args) {
        new Main().run();
    }
    private void run() {
        rw = new RW(FILE_NAME + ".in", FILE_NAME + ".out");
        solve();
        rw.close();
    }
    private class RW {
        private StringTokenizer st;
        private PrintWriter out;
        private BufferedReader br;
        private boolean eof;
        RW(String inputFile, String outputFile) {
            br = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(new OutputStreamWriter(System.out));
            File f = new File(inputFile);
            if (f.exists() && f.canRead()) {
                try {
                    br = new BufferedReader(new FileReader(inputFile));
                    out = new PrintWriter(new FileWriter(outputFile));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        private String nextLine() {
            String s = "";
            try {
                s = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return s;
        }
        private String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    eof = true;
                    return "-1";
                }
            }
            return st.nextToken();
        }
        private long nextLong() {
            return Long.parseLong(next());
        }
        private int nextInt() {
            return Integer.parseInt(next());
        }
        private void println() {
            out.println();
        }
        private void println(Object o) {
            out.println(o);
        }
        private void print(Object o) {
            out.print(o);
        }
        private void close() {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            out.close();
        }
    }
}

Separate the Numbers Solution in Python

def ok(s):
    return s == "0" or s[0] != "0"
def can(s, x):
    n = len(s)
    s += 'x'*100
    p = 0
    while p < n:
        t = str(x)
        if s[p:p+len(t)] != t:
            return False
        x += 1
        p += len(t)
    return True
def solve(s):
    for i in range(1, len(s)):
        t = s[:i]
        if ok(t) and can(s, int(t)):
            print "YES", t
            return
    print "NO"
n = int(raw_input())
for i in range(n):
    solve(raw_input())

Separate the Numbers Solution using 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 ////////////////////
function foundRound(s, len){
    var length = len;
    var curr = s.substring(0, length);
    for(var i=length; i < s.length; i+= length){
        if(s[i] === '0'){
            return false;
        }
        
        var all = true;
        for(var j = 0; j < curr.length; j++){
            if(parseInt(curr[j]) % 10 !== 9){
                all = false;
            }
        }
        if(all === true){
            length++ ;
            
            curr = '1';
            for(var j=0; j < length-1; j++){
                curr += '0';
            }
        }
        else{
            var string = curr;
            var index = string.length-1;
            while(index>-1 && string[index]==='9'){
                string[index] = '0';
                index--;
            }
            var newValue = parseInt(string[index]) + 1;
            curr = string.substring(0,index) + newValue.toString();
            while(index < string.length-1){
                index++;
                curr += '0';
            }
            
        }
        
        if(i + length > s.length){
            return false;
        }
        
        var next = s.substring(i, i + length);
        if(curr !== next){
            return false;
        }
    }
    return true;
}
function main() {
    var q = parseInt(readLine());
    for(var a0 = 0; a0 < q; a0++){
        var s = readLine();
        // your code goes here
        if(s.length < 2 || s[0]==='0'){
            console.log('NO');
        }
        else{
            var found = false;
            for(var len = 1; len <= s.length/2 && !found; len++){
               var answer = foundRound(s, len);
               if (answer === true){
                    console.log('YES ' + s.substring(0,len));
                    found = true;
               }
            }
            if(!found){
                console.log('NO');
            }
        }
    }
}

Separate the Numbers Solution in Scala

import scala.io.StdIn
    
object Solution {
    def main(args: Array[String]) {
        val q = StdIn.readInt()
        (0 until q) foreach { i =>
            val s = StdIn.readLine()
            val x = (1 to s.length / 2) flatMap { j => test(s, j) }
            println(if (x.length > 0) s"YES ${x.min}" else "NO")
        }
    }
    
    def test(s: String, i: Int): Option[Long] = {
        def _test(s: String, n: Long): Boolean =
            if (s.isEmpty) true
            else {
                val t = n.toString
                if (s.startsWith(t)) _test(s.substring(t.length), n + 1)
                else false
            }
        val n = s.substring(0, i).toLong
        if (_test(s.substring(i), n + 1)) Some(n) else None
    }
}

Separate the Numbers Solution in Pascal

var
   arr:array[1..2000] of longint;
  i,j,k,c,casos,L,n:longint;
  cad,aux:string;
  si:boolean;
  res:int64;
procedure compara(i,t,a:int64);
var
   x:int64;
   j:longint;
begin
   if i=L+1 then
      si:=true
   else
   if i=1 then
   begin
      x:=0;
      for i:=1 to L div 2 do
      begin
         x:=10*x+ord(cad[i])-ord('0');
         compara(i+1,i,x);
         if si then
         begin
            res:=x;
            exit;
         end;
         if cad[1]='0' then
           exit;
      end;
   end
   else
   if t+i-1<=L then
   begin
      if cad[i]='0' then
         exit;
      x:=0;
      for j:=i to t+i-1 do
          x:=10*x+ord(cad[j])-ord('0');
      if x<=a then
      begin
         if t+i>L then
            exit;
         x:=10*x+ord(cad[t+i])-ord('0');
         t:=t+1;
      end;
      if x=a+1 then
         compara(i+t,t,x);
   end;
end;
begin
   readln(casos);
   for c:=1 to casos do
   begin
      readln(cad);
      L:=length(cad);
      if L=1 then
         si:=false
      else
        si:=true;
      if si then
      begin
         si:=false;
         compara(1,1,-1);
      end;
      if si then
         writeln('YES ',res)
      else
         writeln('NO');
   end;
end.

Disclaimer: This problem (Separate the Numbers) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Funny String Solution

Leave a Reply

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