Google Interview Question


Country: United States




Comment hidden because of low score. Click to expand.
5
of 5 vote

public String formatString(String stringToSplit, int num){

        String replacedString = Pattern.compile("-").matcher(stringToSplit).replaceAll("");
        char[] chars = replacedString.toCharArray();
        int i = chars.length-1;
        StringBuilder sb = new StringBuilder();
        while (i > num){
            sb.insert(0, chars, i-num+1, num);
            sb.insert(0, "-");
            i -= num;
        }
        sb.insert(0, chars, 0, i+1);
        return sb.toString();
    }

- Upen October 25, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

def splitgroups(A,K):
    A=A.replace("-","")
    A=list(A)
    for i in range(len(A)-K,0,-K):
        A.insert(i,"-")
    A="".join(A)
    return A

print splitgroups("2-4a0r7-4k",3)

- Meteo October 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

private static String reformat(String s, int k) {
        int len = s.length();
        StringBuilder res = new StringBuilder();

        int count = 0;
        for (int i = len - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (c != '-') {
                if (count == k) {
                    res.append("-");
                    count = 0;
                    i++;
                } else {
                    res.append(c);
                    count++;
                }
            }
        }

        return res.reverse().toString();
    }

- tryhard October 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public String reformat(String str, int k){
	if(str == null || str.length() == 0 || k <= 0 || k > str.length()){
		return null;
	}
	if(k == str.length()){
	return str;
	}
	
	int len = 0;
	for(int i = 0; i < str.length(); i++){
		if(str.charAt(i) != '-'){
			len++;
		}
	}
	int rem = len % k;//0
	StringBuilder bldr = new StringBuilder(str.length());
	int i = 0;
	while(i < rem){
		
			if(str.charAt(i) != '-'){
				bldr.append(str.charAt(i))
			}
		
		i++;
	}
	if(i != 0){
		bldr.append('-');
	}
	while(i < str.length()){
		int count = 0;
		while(count < k){
			if(str.charAt(i) != '-'){
				bldr.append(str.charAt(i))
				count++;
			}
			i++;
		}
		if(i < str.length()){
			bldr.append('-');
		}
	}
	return bldr.toString();

}
//O(N) time where N is the length of the input string. O(N) Space.

- divm01986 October 20, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// ZoomBA
def group( s, k ){
  s = s.replace('-','')
  len = #|s|
  rreduce ( s.value ) -> {
    (( $.index != 0 && k /? ( len - $.index) )?'-':'') +
    $.item + $.prev }
}
s = "2-4a0r7-4k"
println ( group ( s, 2 ) )
println ( group ( s, 3 ) )
println ( group ( s, 4 ) )
println ( group ( s, 5 ) )

- NoOne October 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<stdlib.h>


void str_concat(char*s1,char*s2){
  int p=0;
  while(s1[p]!='\0'){
    p++;
  }
  int q=0;
  while(s2[q]!='\0'){
    s1[p] = s2[q];
    p++;
    q++;
  }
  s1[p]='\0';
}

int main(){
  char *A;
  int k=0;
  A = malloc(sizeof(char)*1000);
  scanf("%s",A);
  scanf("%d",&k);

  char *result,*temp;
  result = malloc(sizeof(char)*1000);
  temp = malloc(sizeof(char)*1000);
  int i=0,j=0,len=0;

  while(A[i]!='\0'){
    if(A[i]!='-'){
      len++;
    }
    i++;
  }

  i=0;
  while(i<(len%k)){
    if(A[i]=='-'){
      i++;
      continue;
    }
    result[j]=A[i];
    j++;
    i++;
  }

  if(j>0){
    result[j]='-';
    j++;
  }

  result[j]='\0';
  int l=0;


  while(A[i]!='\0'){
    if(A[i]=='-'){
      i++;
      continue;
    }else{
      if((l+1)%(k+1)==0){
        temp[l]='-';
        l++;
      }
      temp[l]=A[i];
      l++;
    }
    i++;
  }
  temp[l]='\0';

  str_concat(result,temp);
  printf("\n%s",result);
  printf("\n");
  return 0;
}

- ashish October 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n) solution:

public String format(String str, int k){
	int size = str.length();
	char[] chars = str.toCharArray();

	StringBuilder sb = new StringBuilder();

	for(int i = size - 1; i >= 0; i++){
		sb.append(chars[i]);
		if((i + 1) % k == 0)
			sb.append(“-”);
	}

	return sb.reverse().toString();
}

- libertythecoder October 21, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Slight modification to libertythecoder's code. Please correct me if I'm wrong

public String formatString(String s , int k){
		StringBuilder sb = new StringBuilder();
		int counter = 0;
		for(int i = 0; i < s.length() ; i++){
			if(Character.isLetterOrDigit(s.charAt(i))){
				sb.append(s.charAt(i));
				counter++;
			}
			if(counter == 3){
				counter = 0;
				sb.append("-");
			}
		}
		return sb.toString();
	}

- tylerdurden October 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Passed tests

public String format(String S, int K) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < S.length(); i ++) {
            if (S.charAt(i) != '-') {
                builder.append(S.charAt(i));
            }
        }
        StringBuilder result = new StringBuilder();
        String ori = builder.toString();

        int i = ori.length() - 1;
        int stop = (ori.length() - 1) % K;

        while (i >= 0) {
            if (i % K == stop && i != ori.length() - 1)
                result.append('-');
            result.append(Character.toUpperCase(ori.charAt(i)));
            i -= 1;
        }
        return result.reverse().toString();
    }

- hp October 22, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		int num = sc.nextInt();

		str = str.replaceAll("-", "");
		if (str.length() > num) {
			str = reFormatString(str, num);
		}

		System.out.println(str);
		sc.close();
	}

	public static String reFormatString(String str, int num) {
		str = str.replaceAll("-", "");
		StringBuffer sb = new StringBuffer(str);
		sb.reverse();
		for (int i = num; i < sb.length(); i = i + num) {
			sb.insert(i, "-");
			i++;
		}
		sb.reverse();

		return sb.toString();
	}

- Mayank October 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		int num = sc.nextInt();

		str = str.replaceAll("-", "");
		if (str.length() > num) {
			str = reFormatString(str, num);
		}

		System.out.println(str);
		sc.close();
	}

	public static String reFormatString(String str, int num) {
		str = str.replaceAll("-", "");
		StringBuffer sb = new StringBuffer(str);
		sb.reverse();
		for (int i = num; i < sb.length(); i = i + num) {
			sb.insert(i, "-");
			i++;
		}
		sb.reverse();

		return sb.toString();
	}

- Mayank October 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args) 
	{
		Scanner sc = new Scanner(System.in);
		String input = sc.next();
		int k = sc.nextInt();
		System.out.println(Format(input, k) );
	}
	
	public static String Format(String args,int k) 
	{
		StringBuilder s =  new StringBuilder();
		int count=0;
		int len =0;
		for(String str : args.split("-"))
		{
			len = len +str.length();
		}
		
		char [] chararr =args.toCharArray(); 
		for(int i=chararr.length-1;i>=0;i--)
		{
			char c = chararr[i];
			if(c!='-')
			{
				s.append(Character.toString(c));
				count++;
				if(count%k==0&& count!=len)
				{
					s.append("-");
				}
			}
			
			
		}
		return s.reverse().toString();

}

- karldren8 October 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String formattedString(String original, int size){
            if(original == null || size < 1 || original.length() < 1)
                    return "";

            int length = original.length();  
            int currIndex = length - 1; 


            StringBuilder result = new StringBuilder(length + (length / size) + 1);

            while(true){
                int finalIndex = currIndex - size;

                while(currIndex >= 0 && currIndex > finalIndex){
                    if(original.charAt(currIndex) == '-'){
                        finalIndex--;
                    }else{
                        result.insert(0, original.charAt(currIndex));
                    }
                    currIndex--;

                }



                if(currIndex > 0){
                    result.insert(0,'-');
                }else{
                    break;
                }
            }

            return result.toString();
    }

- Eugenio Kuri October 23, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

From my point of view they want to "split" a string into groups separated by dash and tehy provide the number of elements in the group so assuming that please find below my solution:

//FUNCTION TO SPLIT A STRING WITH A DASH GIVEN THE NUMBER OF ELEMENTS PER GROUP
-(NSString *)getFormatString:(NSString *)string withSplitItems:(int)split{
    
    NSMutableString *result = [NSMutableString new];
    
    //REPLACE ALL DASHES SINCE THEY DO NOT MENTION TO KEEP IT
    string = [string stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    int length = (int)[string length];
    int j = -1;
    
    //ITERATE BETWEEN ALL CHARACTERS IN THE STRING FROM THE END TO THE START
    for(int i = length - 1; i >= 0; i--){
        
        //IF OUR SECONDARY COUNTER IS EQUAL TO THE GIVEN INDEX SET A DASH
        j++;
        if(j == split){
            result = [result stringByAppendingString:@"-"];
            j = 0;
        }
        
        //ADD EACH CHARACTER
        [result insertString:[string substringWithRange:NSMakeRange(i, 1)] atIndex:0];
    }
    
    return result;
}

- oscarsanchez1937 October 24, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringGroup {

	// ----------------------------------------------------------------

	public static String groupString(String inp, int grpLen) {
		
		String grp = "";
		int stringLen = inp.length();

		StringBuffer inpString = new StringBuffer();

		for (int i = 0; i < inp.length(); i = i + grpLen) {
			
			if (stringLen >= grpLen) {
				
				stringLen = stringLen - grpLen;
				grp = inp.substring(i, i + grpLen);
				inpString.append(grp + "-");

			} else {
				
				grp = inp.substring(i, inp.length());
				inpString.append(grp);
				
			}
		}

		return inpString.toString();
	}

	public static void main(String[] args) {
		
		String inp = "California";
		groupString(inp, 3);
		
	}
}

- Sandy0109 October 26, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Relatively simple problem. Using StringBuilder (or StringBuffer) is the key here.

public class StringFormatLengthK {

    public String reformatString(String input, int k){
        if(input == null || input.length() == 0){
            return null;
        }

        String[] arr = input.split("-");

        StringBuilder sbTemp = new StringBuilder();
        for(String str : arr){
            sbTemp.append(str);
        }
        String plainString = sbTemp.toString();
        System.out.println("plainString: "+plainString);
        int counter = 1;

        StringBuilder sb = new StringBuilder();
        for(int i = plainString.length()-1; i >= 0; i--){
            String str = plainString.substring(i, i+1);
            sb.append(str);

            if(counter == k) {
                sb.append("-");
                counter = 0;
            }
            counter++;
        }
        String lastChar = sb.substring(sb.length()-1);
        if("-".equals(lastChar)){
            sb.deleteCharAt(sb.length()-1);
        }
        sb.reverse();
        return sb.toString();
    }

    public static void main(String[] args) {
        StringFormatLengthK stringFormatLengthK = new StringFormatLengthK();
        String input = "2-4a0r7-4k";
        String reformattedString = stringFormatLengthK.reformatString(input, 5);

        System.out.println("reformatted: "+ reformattedString);
    }

}

- jsayyy October 30, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def resplit(s, k):
	s = ''.join(s.split('-'))
	out = []
	while s:
		out.append(s[-k:])
		s = s[:-k]
	return '-'.join(out[::-1])

- KingMouse November 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def format_str(A, k):
    j = len(A) - 1
    B = ""
    m = k
    
    while j >= 0:
        if A[j] == "-":
            j -= 1
            continue
        if m == 0:
            m = k
            B += "-"
        B += A[j]
        m -= 1
        j -= 1
    
    return B[::-1]

- Gates_ice November 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def format_str(A, k):
    j = len(A) - 1
    B = ""
    m = k
    
    while j >= 0:
        if A[j] == "-":
            j -= 1
            continue
        if m == 0:
            m = k
            B += "-"
        B += A[j]
        m -= 1
        j -= 1
    
    return B[::-1]

- Gates_ice November 04, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String split(String input, int k){
		if(input==null){
			return null;
		}
		int strLength = input.length();
		if(strLength<=k){
			return input;
		}
		StringBuilder stringBuilder = new StringBuilder();
		int count= 0;
		for(int i=0;i<strLength;i++){
			char current = input.charAt(i);
			if(count<k && current!='-'){
				stringBuilder.append(current);
				count++;
			}else if (count==k && current != '-'){
				stringBuilder.append('-').append(current);
				count=0;
			}
		}
		return stringBuilder.toString();

}

- d1nOnly November 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Main {

    public static void main(String[] args) {
	// write your code here

        String unformatted ="2k-432iz-kdf";
        Main main = new Main();

        System.out.println(main.formatInSectionsOfSize(unformatted, 3));
    }

    public String formatInSectionsOfSize(String incoming, int sectionSize) {
        LinkedList<Character> chars = new LinkedList<Character>();

        for(int i = 0; i < incoming.length(); i++) {
            char current = incoming.charAt(i);
            if(current != '-') {
                chars.addLast(current);
            }
        }

        StringBuilder stringBuilder = new StringBuilder();

        int firstSection = chars.size() % sectionSize;

        if(firstSection > 0) {
            for(int i = 0; i < firstSection; i++) {
                stringBuilder.append(chars.removeFirst());
            }
            stringBuilder.append("-");
        }

        int remainingSize = chars.size();

        for(int i = 0; i < remainingSize; i++ ) {
            stringBuilder.append(chars.removeFirst());
            if( (i % sectionSize) == (sectionSize - 1) && i != (remainingSize - 1)) {
                stringBuilder.append("-");
            }
        }

        return stringBuilder.toString();
    }
}

- montwell November 06, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String A = "2-4a0r7-4k-asfasf-112";
int K = 3;
String _without_hypens = "";
StringBuilder sb = new StringBuilder();
StringBuilder _hyphen_appended = new StringBuilder();
int count = 0;
String _with_hyphens_rev = "";
String _with_hyphens = "";
//loop to get all the characters without hyphens
for(int i=0; i<A.length();i++){
if(!(A.substring(i, i+1).equals("-"))){
sb.append(A.substring(i,i+1));
}
}
_without_hypens = sb.toString();
//loop from the last character to get assign hyphens after crossing K characters
for(int j=_without_hypens.length() -1; j>=0; j--){
_hyphen_appended.append(_without_hypens.substring(j, j+1));
count+=1;
if(count == K && j != 0){
_hyphen_appended.append("-");
count = 0;
}
}
_with_hyphens_rev = _hyphen_appended.toString();

//loop to reverse the string
for(int k = _with_hyphens_rev.length() -1; k>=0; k--){
_with_hyphens+=_with_hyphens_rev.substring(k, k+1);
}

- Mani November 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public String Stringformatter(String A, int K){

String _without_hypens = "";
StringBuilder sb = new StringBuilder();
StringBuilder _hyphen_appended = new StringBuilder();
int count = 0;
String _with_hyphens_rev = "";
String _with_hyphens = "";
//loop to get all the characters without hyphens
for(int i=0; i<A.length();i++){
	if(!(A.substring(i, i+1).equals("-"))){
		sb.append(A.substring(i,i+1));
	}
}

_without_hypens = sb.toString();
		
//loop from the last character to get assign hyphens after crossing K characters
for(int j=_without_hypens.length() -1; j>=0; j--){
	_hyphen_appended.append(_without_hypens.substring(j, j+1));
	count+=1;
	if(count == K && j != 0){
		_hyphen_appended.append("-");
		count = 0;
	}
}

_with_hyphens_rev = _hyphen_appended.toString();
		
//loop to reverse the string
for(int k = _with_hyphens_rev.length() -1; k>=0; k--){
	_with_hyphens+=_with_hyphens_rev.substring(k, k+1);
}

return _with_hyphens;
}

- Mani November 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def format_string(s, k):
    if k == 0:
        return s
    
    s = s.replace("-", "")
    
    index = len(s)%k
    if index == 0: 
        index = k
    
    while index < len(s):
        s = s[:index] + "-" + s[index:]
        index += 1 + k
    
    return s
    
s = "24-A0sjf-jdjf-293#j"
print format_string(s, 5)

- Nitish Garg December 26, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String formatString(String str,int k){
        StringBuilder sb = new StringBuilder();
        char[] array = str.toCharArray();
        int p = 0;
        for(int i=0;i>array.length;i++){
            if(array[i]=='-'){
                continue;
            }
            sb.append(array[i]);
            p++;
            if(p==k){
                sb.append("-");
                p=0;
            }
        }
        
        return sb.toString();
    }

- tiandiao123 October 07, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

public String reformat(String s, int k) {
		if (s.length() == 0 || k <= 0 || k > s.length() || s == null) {
			return null;
		}
		if (k == s.length()) {
			return s;
		}
		return new StringBuilder(new StringBuilder(s).reverse().toString().replaceAll("-", "").replaceAll("(.{" + k + "})", "$1-").replaceAll("-$", "")).reverse().toString();
	}

- cemaivaz October 21, 2016 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More