Separate the Numbers HackerRank Solution in C, C++, Java, Python

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:

You must 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’s 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. It should print a string as described above.

separateNumbers has the following parameter:

  • s: an integer value represented as a string

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] belongs to [0 – 9]

Output Format

For each query, print its answer on a new line (i.e., either YES x where  is the smallest first number of the increasing sequence, or NO).

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.

 

Separate the Numbers HackerRank 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 HackerRank Solution in C++

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define lim 10000007
#define pb push_back
#define S second
#define pb push_back
#define mp make_pair
#define INF 1e18
#define fr(i,j,k) for(ll i=j;i<=k;i++)
#define frd(i,j,k) for(ll i=j;i>=k;i--)
#define F first
#define sd(n) scanf("%lld",&n)
#define pd(n) printf("%lld\n",n)
#define db double
#define mod 1000000007
#define pii pair<ll,ll>
ll nm(string s)
{
    ll ans=0;
    
    for(ll i=0;i<s.length();i++)
        ans=10*ans+s[i]-'0';
    return ans;
}
bool can(string s,ll i,ll val)
{   //cout<<i<<" "<<val<<endl;
if(val==0)
return 0;
    val++;
    if(i>=s.length()-1)
        return 1;
    ll c=0;

    for(ll j=i+1;j<s.length();j++)
    {    if(j==i+1)
        {
            if(s[j]=='0')
                return 0;
        }
        c=10*c+s[j]-'0';
        if(c>val)
            return 0;
        if(c==val)
            return can(s,j,val);

    }
    return 0;

}
int main()
{
    ll t;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;
        if(s[0]=='0')
        {
            cout<<"NO"<<endl;
            continue;
        }
        bool pop=0;
        for(ll i=0;i<s.length()-1;i++)
        {   if(pop)
            break;
            if(can(s,i,nm(s.substr(0,i+1))))
            {
                cout<<"YES "<<nm(s.substr(0,i+1))<<endl;
                pop=1;
                break;
            }
        }
        if(!pop)
        cout<<"NO"<<endl;
    }
}

 

Separate the Numbers HackerRank Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int q = s.nextInt();
        for(int i = 0; i < q; i++){
            String in = s.next();
            long a = check(in);
            if (a != -1) {
                System.out.println("YES " + a);
            }
            else {
                System.out.println("NO");
            }
        }
    }
    
    public static long check(String s) {
        for (int j = 1; j < s.length()+1 && j < 18; j++) {
            long a = Long.parseLong(s.substring(0, j));
            long init = a;
            String temp = "" + a;
            int count = 1;
            while (temp.length() < s.length()) {
                a++;
                count++;
                temp += a;
            }
            if (temp.equals(s) && count >= 2) {
                return init;
            }         
        }
        return -1;
    
    }
}

 

Separate the Numbers HackerRank Solution in Python

q = int(raw_input())
for __ in xrange(q):
    s = raw_input().strip()
    if s[0] == '0':
        print "NO"
        continue
    found = False
    for pref in xrange(1,len(s)+1):
        t = ""
        curnum = int(s[:pref])
        added = 0
        while len(t) < len(s):
            t += str(curnum)
            curnum += 1
            added += 1
        if added > 1 and t == s:
            print "YES", s[:pref]
            found = True
            break
    if not found:
        print "NO"

 

Separate the Numbers HackerRank Solution in C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
/// <summary>
/// Separate the Numbers 
/// https://www.hackerrank.com/contests/university-codesprint-2/challenges/separate-the-numbers
/// </summary>
class Solution2
{
    static bool Beautiful(long A, string S)
    {
        if (string.IsNullOrEmpty(S)) return true;

        string A1 = (A + 1).ToString();
        if (S.StartsWith(A1)) return Beautiful(A + 1, S.Substring(A1.Length));
        return false;
    }
    static void Main(String[] args)
    {
        TextReader tIn = Console.In;
        TextWriter tOut = Console.Out;

        int Q = int.Parse(tIn.ReadLine());
        for (int q = 0; q < Q; q++)
        {
            string S = tIn.ReadLine();
            bool b = false;
            long A = 0;
            for (int i = 1; i <= S.Length / 2; i++)
            {
                A = long.Parse(S.Substring(0, i));
                if (Beautiful(A, S.Substring(i)))
                {
                    b = true;
                    break;
                }
            }
            tOut.WriteLine(b ? string.Format("YES {0}", A) : "NO");
        }
    }
}

 

Attempt Separate the Numbers HackerRank Challenge

Link – https://www.hackerrank.com/challenges/separate-the-numbers/

Next HackerRank Challenge Solution 

Link – https://exploringbits.com/funny-string-hackerrank-solution/

Leave a Comment