Goldman Sachs interview question

Input string aaabbbbcc Output string a3b4c2

Interview Answers

Anonymous

Mar 27, 2018

/** * java program to solve string issue */ public class StringProblem1 { public static void main(String[] args) { String s = "aaabbbbcc"; StringBuffer buf = new StringBuffer(); int len = s.length(); int count = 1; char ch = s.charAt(0); for(int i=1; i< len; i++) { if(s.charAt(i) ==ch) { count++; System.out.printf("%c %d \n",ch, count); } else { buf.append(ch); buf.append(count); count=1; ch = s.charAt(i); System.out.println(buf.toString()); } } buf.append(ch); buf.append(count); System.out.println("Final: " + buf.toString()); } }

Anonymous

Apr 30, 2018

Sorry for using Swift, a newer language not known by many, I don't work with C/++ regularly. But the concept is to create an array initialized with values of 0 of size 128 (corresponding ascii values). Perform different casts to ascii value to char and char to ascii value. Store the occurrences of the character at the character's ascii index. Iterate through the array and append the character and the count. Time : O(n +k) where k is a constant = 128 Space : O(n) func compressString(str : String) -> String{ var countArray : [Int] = Array(repeating: 0, count: 128) var encodedStr = "" for (index,char) in str.enumerated(){ let i = UnicodeScalar(String(char))! countArray[Int(i.value)] += 1 } for (index,num) in countArray.enumerated(){ if countArray[index] != 0 { let char = UnicodeScalar(index)! encodedStr.append("\(char)\(countArray[index])") } } return encodedStr }