Amazon Interview Question for Software Development Managers


Country: United States




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

A little verbose, but hopefully it is easier to understand.

public static StringBuilder buildOutput(StringBuilder bdr, char target,
			int rep) {
		bdr.append(target);
		if (rep > 0) {
			bdr.append(Integer.toString(rep + 1));
		}
		return bdr;
	}

	public static String compressString(String s) {
		StringBuilder buf = new StringBuilder();
		if (s == null || s.length() < 2) {
			return s;
		}

		char cur = s.charAt(0);
		char pre = cur;
		int rep = 0;

		for (int i = 1; i < s.length(); i++) {
			cur = s.charAt(i);
			if (cur == pre) {
				rep++;
			} else {
				buf = buildOutput(buf, pre, rep);
				pre = cur;
				rep = 0;
			}
		}
		buf = buildOutput(buf, pre, rep);
		return buf.toString();
	}

- xdoer February 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

can we do without recursion?

static string Compress(string s)
{
	var ch = s[0];
	var count = 1;
	var output = new StringBuilder();
	for(var i=1;i<s.Length;i++)
	{
		if(s[i] == ch)
		{
			count++;
		}
		else
		{
			output.Append(count == 1 ? ch.ToString() : ch + count.ToString());
			count = 1;
			ch = s[i];
		}
	}
	output.Append(count == 1 ? ch.ToString() : ch + count.ToString());
	return output.ToString();
}

- S.Abakumoff February 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@S.Abakumoff
I don't see any recursion in the solution provided by xdoer, can u explain what you meant by recursion?

- xxx February 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

mea culpa, nevermind

- S.Abakumoff February 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

is the characters coming in an alphabet order? when the input is AABBCCDDAA the output would be A2B2C2D2A2, not A4B2C2D2

- yuz1988@iastate.edu February 26, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Solution does not work if last char in input string is a different from last but one char (e.g jjjjjjjjddddddddddaaaak)

Need to add

if(str.charAt(str.length()-1)!=str.charAt(str.length()-2))
			System.out.println("====="+t_str+str.charAt(str.length()-1)+"1");

- suvrokroy March 01, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It should be if (rep > =0) . Then it works if the last character in the input string is different from the last but one-th character. A;so works if a single character is passed.

- looking_for_solutions March 13, 2013 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 vote

function compress(string toCompress){
	if(toCompress.length() < 2){
		return toCompress;
	}
	string compressed = "";
	char[] charList = toCompress.toCharArray();
	char currentChar = charList[0];
	int currentCount = 1;
	for(int i = 1; i < charList.length; i++){
		if(charList[i] == currentChar){
			currentCount++;
		}else{
			compressed += currentChar + currentCount;
			currentChar = charList[i];
			currentCount = 1;
		}
	}
	return compressed;
}

- firstTimeDummy February 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Will this code work for "ABC"?

- Geet February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

private static String compress(String toCompress){
		if(toCompress.length() < 2){
			return toCompress;
		}
		String compressed = "";
		char[] charList = toCompress.toCharArray();
		char currentChar = charList[0];
		int currentCount = 1;
		for(int i = 1; i < charList.length; i++){
			if(charList[i] == currentChar){
				currentCount++;
			}else{
				compressed += "" + currentChar + "" + currentCount;
				currentChar = charList[i];
				currentCount = 1;
			}
		}
		compressed += "" + currentChar + "" + currentCount;
		return compressed;
	}

- firstTimeDummy February 18, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

static String compress(String string){ 
		int count=0; 
		char prevChar= string.charAt(0); 
		String result=""; 
		char [] charArray=string.toCharArray(); 
		for(char c: charArray){ 
			if(c==prevChar){ 
				count++; 
			}else{ 
				if(count==1){ 
				result= result.concat(new StringBuilder(1).append(c).toString()); 
				}else{
				result= result.concat(prevChar+ Integer.toString(count)); 
				}
				count=1; 
				prevChar=c; 
			}
		}
		result=result.concat(string.charAt(string.length()-1)+ Integer.toString(count)); 
		

		return result; 
		
	}

- I had the same algorithm! February 22, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

public class CompressString {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//AAACCCBBD to A3C3B2D
String str="ABC";
StringBuffer sb=new StringBuffer();
int charcounter=1;
char previouschar=str.charAt(0);
if(str.length()==1){
sb.append(previouschar);
}
if(str.length()>1){

for(int icounter=1;icounter<str.length();icounter++){
if(str.charAt(icounter)==previouschar){
charcounter++;
}
else{

sb.append(previouschar);
if(charcounter!=1){
sb.append(charcounter);
}
charcounter=1;
previouschar=str.charAt(icounter);
}
}
sb.append(previouschar);
if(charcounter!=1){
sb.append(charcounter);
}
}
System.out.println(sb);

}

}

- naveenhooda2004 February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this is not working..???

- smoke February 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

For which testcase ?

- naveenhooda2004 February 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

public static void compressString(String inp) {
		StringBuilder out = new StringBuilder();
		int count = 1;
		for(int i=0;i<inp.length();i++)
		{
			if(i<inp.length()-1 && inp.charAt(i) == inp.charAt(i+1)) {
				count++;
				continue;
			}
			out.append(inp.charAt(i));
			if(count>1) 
				out.append(count);
			count=1;
		}
		System.out.println(out.toString());
	}

- codewarrior February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

when i < inp.length()
and
inp.charAt( i ) == inp. charAt(i+1)
gives
ArrayIndexOutOfBoundsError

- goutham467 February 25, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

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

int main()
{
    char str[] = "AAAAAABBBBBCCCHHHDADAS";
    int i=0, j=0, count=0;
    char c;
    for(i=0;i<strlen(str);i++)
    {
        char c = str[i];
        while(c == str[i])
        {
             count++;
             i++;
        }
        i--;
        str[j++]=str[i];
        itoa(count,(str+j),10);
        str[j+1] = " ";
        j++;
        count = 0;
    }
    str[j] = '\0';
    printf("\n%s",str);
    return 0;
}

- Anonymous February 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

JavaScript solution - O(n)

function compress(content) {
    var character, count, i, result = [];

    for (i = 0; i < content.length;) {
        character = content.charAt(i);

        result.push(character);

        ++i;

        count = 1;

        while (content.charAt(i) === character) {
            ++count;

            ++i;
        }

        if (count > 1) {
            result.push(count);
        }
    }

    return result.join('');
};

- Anonymous February 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void Main()
{
string data = "AABCDDDDEEFFF";
Console.WriteLine("OLD {0} : NEW {1}", data, BuildStringRepresentation(data));
}

// Define other methods and classes here
string BuildStringRepresentation(string data) {
StringBuilder s = new StringBuilder();

if(data.Length <= 1) {
return data;
}

int i = 0, count = 0;
char ch;
while(i < data.Length) {
ch = data[i];
count = 0;

while(i < data.Length - 1 && data[++i] == ch) {
count++;
}

if(i == data.Length - 1) {
i++;
}

s.Append(ch);

if(count > 0) {
s.Append(count+1);
}
}

return s.ToString();
}

- Anonymous February 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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


void addcount(int, int, char*);

int main(int argc, char **argv)
{
	char *string = argv[1];
	char *newstring;
	int len = strlen(string);
	newstring = (char *)malloc(2*len);
	
	int i,j = 0;
	int count = 0;
	char prevch;
	char currch;

	while(string[i] != '\0')
	{
		currch = string[i];
	
		if(currch == prevch || i == 0)
		{
			count++;
			i++;
			prevch = currch;
			continue;
		}
		/*else if(currch != prevch && prevch == NULL)
		{
			count++;
			i++;
			prevch = currch;
			continue;
		}*/
		else{
			newstring[j] = prevch;
			addcount(j+1, count, newstring);
			j+=2;
			count = 1;
			i++;
			prevch = currch;
			continue;
		}
	}

	newstring[j] = prevch;
	addcount(j+1, count, newstring);
	//newstring[j+1] = itoa(count);
	newstring[j+2] = '\0';
	
	printf("this is original string: %s\n", string);
	printf("this is new string: %s\n", newstring);

	return;
}


void addcount(int j, int count, char *nstring)
{
	int chararray[10] = {48,49,50,51,52,53,54,55,56,57};
	
	if(count < 10)
	{
		nstring[j] = chararray[count];
	}else if(10 < count < 100)
	{
		int n1 = count/10;
		int n2 = count%10;
		nstring[j++] = chararray[n1];
		nstring[j++] = chararray[n2];
	}
}

- vijayh February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

What if a character repeats 1000 times? :(

- DrFrag February 21, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

scala> def pack(s: String, r: String): String = s match {
     |  case "" => r
     |  case _ => val (x,y) = s.tail.span(_ == s.head)
     |   val v = if(x == "") s.head.toString else s.head+(x.length+1).toString
     |   pack(y,r+v)
     | }
pack: (s: String, r: String)String

scala>  pack("AAABBCCCDA","")
res13: String = A3B2C3DA

- rbsomeg February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is Java Program
inArr is we can create the char array and outPut array.

public class CompressingArray {
	int count1=1,i, count2, count3;
	char[] inArr = { 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'X', 'X', 'T', 'T',
			'T', 'T' };
	char[] outArr = new char[20];

	public char[] compress() {
		for ( i = 0; i < (inArr.length-1); i++) {
			if (inArr[i] == inArr[(i + 1)]) {
				count1++;
				//System.out.println(count1);
			} else {
				System.out.print(""+(char)inArr[i]+count1);
				count1 = 1;
			}
		}System.out.print(""+(char)inArr[i]+count1);
		return outArr;
	}

	public static void main(String[] args) {
		new CompressingArray().compress();

	}
}

- Md Husain February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

``` javascript
function parse(s){
for (i=0, a=[], r=1; i<s.length;i++){
if (s[i] === s[i+1]){
r++;
}else{
a.push(s[i]+(r===1? '':r));r=1;
}
} return a.join('')
}
```

- Mohsen February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

import java.util.Arrays;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

public class Test {
	static LinkedHashMap<String, Integer> ht = new LinkedHashMap<String, Integer>();

	public static void main(String[] args) {
		String array[] = { "A", "A", "A", "C", "C", "C", "B", "B", "D" };
		int length = array.length;
		for (int i = 0; i < length; i++) {
			String value = array[i];
			if (ht.containsKey(value)) {
				int count = ht.get(value);
				ht.put(value, ++count);
			} else {
				ht.put(array[i], 1);
			}

		}
		int k = 0;
		Set set = ht.keySet(); // get set-view of keys
		Iterator itr = set.iterator();
		while (itr.hasNext()) {
			String str = (String) itr.next();
			array[k] = str;
			k++;
			array[k] = ht.get(str).toString();
			k++;
		}
		array = Arrays.copyOf(array, k - 1);
		for (int i = 0; i < array.length; i++) {
			System.out.println(array[i]);
		}

	}

}

- Sampada February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this is not compressed ..its only count the letter .
for try put input BAACCBBCCD.?

- smoke February 20, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Well My Algo goes here.

1> set pointer *p=(char *)GivenString;
2> set int counter=0; string s;
2> While (*p)
{
set pointer *p1=p+1;
while(*p==*p1){
counter=counter++;
}
set String s=s+*p+counter;
}

Have I Missed any usecase ?

- Prem February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is the solution for this problem using c/cpp. I checked this for few condition, please let me know if it is wrong...

int CheckString(const char *pcString)
{
if( pcString == NULL )
return 1;

char cCurr;
char cPrev;

int iCounter = 0;
int iRepeatCount = 1;

while( pcString[iCounter] != '\0' )
{
cPrev = pcString[iCounter];
iRepeatCount = 1;
for(int iCharTraverse = iCounter + 1; pcString[iCharTraverse] == cPrev; iCharTraverse ++)
{
cCurr = pcString[iCharTraverse];
if( cPrev == cCurr )
{
iRepeatCount ++;
iCounter++;
}
}

if( iRepeatCount > 1)
printf("%c%d", cPrev, iRepeatCount);
else
printf("%c", cPrev);

iCounter++;
}
return 0;
}



int main(int argc, CHAR** argv)
{
CheckString("AAACCCBBD");
//output will be : A3C3B2D
return 0;
}

- kuber February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<string.h>

int main()
{
	char str[100],c;
	int i,len,idx=0,count=1;
	scanf("%s",str);
	len=strlen(str);
	c=str[0];
	for(i=1;i<len;i++)
	{
		if(str[i]==c)
			++count;
		else
		{
			str[idx++]=c;
			if(count>1)
			str[idx++]=count+'0';
			c=str[i];
			count=1;
		}
	}
	str[idx++]=c;
	if(count>1)
	str[idx++]=count+'0';
	str[idx]='\0';
	printf("\n%s",str);
return 0;

}

- kaiser February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

what if string is "abcd" should we make it " a1b1c1d1 " ?

- AK February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

that would not make sense, so at the end I would say to check the length of original string with compressed string and if compressed string length is larger than original, let the program return the original string

- Ashish19121 March 07, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<conio.h>
int main()
{
char a[]="aaabbcccddfffff";
int count[256]={0},i=0,l=0;
l=strlen(a);

for(i=0;i<l;i++)
count[a[i]]++;

for(i=0;i<l;i++)
{
printf("%c%d",a[i],count[a[i]]);
i+=count[a[i]]-1;
}
getch();
}

- Anonymous February 19, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def compressString(string):
  count = 1
  re = ''
  tag = string[0]
  
  for i in range(1, len(string)):
    if tag == string[i] and i != len(string) - 1:
      count += 1
    elif i == len(string) - 1:
      if tag == string[i]:
        count += 1
        re = re + tag + str(count)
      else:
        re = re + tag + str(count) + string[i]
        print id(re)
    else:
      re = re + tag + str(count)
      count = 1
      tag = string[i]
      
  return re if len(re) < len(string) else string
  
print compressString('aaaaaaadddddddddkkkkkkkk')

- Python February 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I can only provide pseudo-code

str = "AAACCCBBD";
int n = strlen(str);
Int j = 1;
for (i = 0; i < n; i++){
  if (j == 1) print str[i];
  if(str[i+1] == str[i]) j++;
  else { print j; j = 1;}
}

- Deepak February 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <string>
#include <vector>
#include <map>

using namespace std;

string compress(const string& in)
{
  map<char,int> m;
  map<char,int>::iterator it;
  vector<char>  v;

  char buf[10];
  string out;

  size_t s = in.length();
  for(size_t i=0; i<s; i++)
  {
    char ch = in[i];
    it = m.find(ch);
    if(it != m.end())
      it->second++;
    else
    {
      m.insert(pair<char,int>(ch,1));
      v.push_back(ch);
    }
  }
  for(vector<char>::iterator vi=v.begin(); vi<v.end(); vi++)
  {
    char ch = *vi;
    it = m.find(ch);
    sprintf_s(buf,10,"%c%i",ch,it->second);
    out += buf;
  }
  return out;
}

- dubovoy.vladimir February 20, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<cstdio>
using namespace std;
int main()
{
    string str;
    cout<<"Enter string to compress: ";
    cin>>str;
    int j=1;
    char c = str[0];
    string op;
    op += c;
    char buff[5];
    for(int i=1;i<str.length();++i)
    {
        if(c!=str[i])
        {
            sprintf(buff,"%d",j);
            op += buff;
            op +=str[i];
            j = 1;
        }
        else
        {
            ++j;
        }
        c = str[i];
    }
    sprintf(buff,"%d",j);
    op += buff;
    cout<<op<<endl;
    return 0;
}

- pathak February 21, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void compress(char *str){
	int i = 0, x = 1, counter = 1;

	while(str[i] != '\0'){
		while(str[i] == str[x]){
			x++;
			counter++;
		}
		cout << str[i] << counter;
		i = x;
		x = i + 1;
		counter = 1;
	}
}

- Punit Patel February 22, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void stringCompress(String a){
		int size = a.length();
		System.out.println("Size = " + size);
		char chararray[] = a.toCharArray();
		char char1, char2;
		int charlength = 1 , i=1;
		if(size == 0) {
			System.out.println("No characters present");
			return;
		}
		if(size == 1){
			System.out.println(chararray[0]+"1");
			return;
		}
		char1 = chararray[0];
		char2 = chararray[1];
		while(i<size) {
			char2 = chararray[i];
			if(char1 == char2) {
				charlength++;
			}
			else {
				System.out.print(char1+""+charlength);
				charlength = 1;
			}
			char1 = char2;
			i++;
		}
		if(char1==char2) {
			System.out.print(char1+""+charlength);
			}
	}

- sgum February 24, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

string compress(string s)
{
    string result;
    int count = 1;

    for (int i = 0; i < s.length(); i++) {
        if (s[i] == s[i + 1]) {
            count++;
            continue;
        } else {
            result = result + s[i];
            char n[20];
            sprintf(n, "%d", count);
            result = result + n;
            count = 1;
        }
    }

    if (result.length() > s.length())
        return s;
    else
        return result;

}

- Ashish19121 March 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public void compressString(String value){
		char[] values = value.toCharArray();
		StringBuilder sb = new StringBuilder("");
		char prev = values[0];
		int count = 1;
		for(int i =1 ; i<= values.length ; i++){
			if(i<values.length){
				if(values[i] == prev){
					count++;
				}
				else{
					sb.append(prev);
					if(count > 1){
						sb.append(count);
					}
					
					prev = values[i];
					count = 1;
				}
			}
			else{
				sb.append(prev);
				if(count > 1){
					sb.append(count);
				}
			}
		}
		System.out.println(sb.toString());
	}

- sudharshan.nn March 07, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

PrintCompressed("AAACCCBBDXXXXEEEE!!!!GGGGAQ!WDFGGGGGH");
        Result: A3C3B2DX4E4!4G4AQ!WDFG5H

        public void PrintCompressed(string chars)
        {
            var charArray = new List<char>();
            var countArray = new List<int>();

            //add the first
            charArray.Add(chars[0]);
            countArray.Add(1);

            //loop through the rest
            for (int c = 1; c < chars.Length; c++)
            {
                if (chars[c - 1] != chars[c])
                {
                    charArray.Add(chars[c]);
                    countArray.Add(1);        
                }
                else
                {
                    countArray[charArray.Count() - 1]++;
                }
            }
            //build the string to print
            var stringBuilder = new StringBuilder();
            for (int i = 0; i < charArray.Count(); i++)
            {
                stringBuilder.AppendFormat("{0}{1}", charArray[i], countArray[i] > 1 ? countArray[i].ToString() : "");
            }
            //print
            Console.WriteLine(stringBuilder.ToString());

}

- Anonymous August 10, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void compress(char* input){
	int i = 0;
	char cur;
	int count = -1;
	char prev= -1;
	while(input[i]){
		cur = input[i];
		if (cur == prev){
			count++;
		}
		else{
			if (count != -1)
				print(prev, count);
			prev = cur;
			count = 1;
		}
                i++
	}
	if (count != -1)
		print(cur, count);
}

- sjuusa October 25, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python 

string = "AAAAABBBBBCCCDDDDDDDDDEEF"
adict = {}
cat_string = ""

for x in string: adict[x] = 1 if x not in adict.keys() else 1+adict[x]
for key in sorted(adict.keys()): cat_string += "%s%s" % (key,adict[key])

print (cat_string)

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

1 #!/usr/bin/python
2
3 string = "AAAZZZZZAABBBEGGGGGBBCCCDDDDDZZZDDDDEEFZZZZZZZZZZZZ"
4 adict = {}
5
6 for x in string: adict[x] = 1 if x not in adict.keys() else 1+adict[x]
7 print (''.join(["%s%s" % (x[0],x[1]) for x in sorted(adict.items())]))

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

1 #!/usr/bin/python
  2 
  3 string = "AAAZZZZZAABBBEGGGGGBBCCCDDDDDZZZDDDDEEFZZZZZZZZZZZZ"
  4 adict = {}
  5 
  6 for x in string: adict[x] = 1 if x not in adict.keys() else 1+adict[x]
  7 print (''.join(["%s%s" % (x[0],x[1]) for x in sorted(adict.items())]))

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

from collections import OrderedDict


def count_chars(s):
  d = OrderedDict()
  for i in range(len(s)):
    if s[i] in d:
      d[s[i]] += 1
    else:
      d[s[i]] = 1
  return d


def combine_str_count(d): 
  res = ''
  for k, v in d.items():
    # handle special case of not printing 1
    if v == 1:
      v = ''
    res = ''.join([res, str(k), str(v)])
  return res


def compress_string(s):
  d = count_chars(s)
  return combine_str_count(d)

if __name__ == "__main__": 
  print(compress_string("AAACCCBBD"))

- some_dude January 05, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

from collections import OrderedDict


def count_chars(s):
  d = OrderedDict()
  for i in range(len(s)):
    if s[i] in d:
      d[s[i]] += 1
    else:
      d[s[i]] = 1
  return d


def combine_str_count(d): 
  res = ''
  for k, v in d.items():
    # handle special case of not printing 1
    if v == 1:
      v = ''
    res = ''.join([res, str(k), str(v)])
  return res


def compress_string(s):
  d = count_chars(s)
  return combine_str_count(d)

if __name__ == "__main__": 
  print(compress_string("AAACCCBBD"))

- some_dude January 05, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

public static String compress(final String str) {
        final StringBuilder builder = new StringBuilder();

        if ((str == null) || str.isEmpty()) {
            return "0";
        }

        builder.append(str.charAt(0));

        int count = 1;

        for (int i = 1; i < str.length(); i++) {
            if (str.charAt(i) == str.charAt(i - 1)) {
                count++;
            } else {
                builder.append(count);
                builder.append(str.charAt(i));

                count = 1;
            }
        }

        builder.append(count);

        return builder.toString();
    }

- Jack February 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This needs a little tweaking as it ADDS two characters to the output when an input character does not repeat.
So optimum compression is not achieved.
eg: input = abc
output = a1b1c1

- DrFrag February 21, 2013 | Flag
Comment hidden because of low score. Click to expand.
-2
of 2 vote

void compress(char *str,int size)
{
if(!(*str))
return;
int index=0;
for(int i=0;i<(size-1);i++)
{
int j=1;
str[index++]=str[i];
while(str[i]==str[i+1])
{
i++;
j++;
}
if(j>1)
str[index++]=j+48;
}
memset(str+index,'\0',size-index);
}

- Anonymous February 18, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Those who marked this solution negative can you please tell me for which input it is getting failed.. Tested some input getting right answer.

- Anonymous February 19, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It does not work for abc: expected output - a1b1c1

- unknown August 24, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It does not work if character is repeated more than 255 times.

- uniknown August 24, 2013 | Flag


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