Amazon Interview Question for Software Engineer / Developers






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

Check my solution:

static string CompressString(string str)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }
            if (str.Length < 2)
            {
                return str;
            }
            var chars = str.ToCharArray();
            int insertIndex = 0;
            int i = 0;
            while (i < chars.Length)
            {
                int j = i + 1;
                int counter = 1;
                while (j < chars.Length && chars[j] == chars[i])
                {
                    i++;
                    j++;
                    counter++;
                }
                chars[insertIndex] = chars[i];
                if (counter > 1)
                {
                    var countAsString = counter.ToString();
                    foreach (var theChar in countAsString)
                    {
                        chars[++insertIndex] = theChar;
                    }
                }
                insertIndex++;
                i = j;
            }
            return new string(chars, 0, insertIndex);
        }

- Anonymous January 22, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Does you code work for "abbb".
The output should come as "a1b3"

- Jit January 23, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorry. I thought that it should be ab3.

- Anonymous January 23, 2011 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

this prog works

public class Trystring {

/**
* @param args
*/
public static void main(String[] args) {

String str= "aaaabbcccc";
StringBuffer str1 = new StringBuffer(str);
System.out.println("Input string is "+str1);
char prev = str1.charAt(0);
char curr;
int count=1,prev_index=0;
for(int i=1;i<str1.length();i++)
{
curr= str1.charAt(i);
if(prev==curr)
count++;
else
{
if(count>2)
{
int offset= prev_index+count;
str1.delete(prev_index+1,offset);
str1.insert(prev_index+1, count);
count=1;
prev = curr;
prev_index = prev_index+2;
i=prev_index;
}
else
{
str1.deleteCharAt(prev_index+1);
str1.insert(prev_index+1, count);
count=1;
prev=curr;
prev_index=prev_index+2;
}
}
if(i==(str1.length()-1))
{

int offset= prev_index+count;
str1.delete(prev_index+1,offset);
str1.insert(prev_index+1, count);

}
}
System.out.println("Output string is " +str1);
}
}

- Sirisha January 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

A simple choice is to scan from one end using normal "two-pointer-string-inplace-delete" way.

But the had point is here:

abcabcaaaaaaaaaaaaabc -> a1b1c1a1b1c1a13b1c1

You cannot normally start from any end.

I will do such thing to fix:

1. first scan, for every substring like "aaaa" other than "a", compress to "a4", leave any "a1" untouched.
2. second scan, from end to start, using two pointer, inplace move all the space to the front, characters to the tail.
3. third scan, from start to end, using two pointer, inplace move all the characters to the front, unfold "a"s to "a1"s on the way.

- Zhen January 22, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

I do not think that the second scan is needed.Just the first scan and the third scan is perfect to solve this problem.

- will January 27, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

<pre lang="c++" line="1" title="CodeMonkey89025" class="run-this">//Using Recursion
#include<iostream>
#include<string.h>
using namespace std;
char b[100];
static int noof_times=1,index=0;

char compress(char *a,char c,int p,int ,int )
{
if(p==-1)return c;
char t=compress(a,a[p],p-1,index,noof_times);
if(t==c)noof_times++;
else
{
a[index++]=t;
a[index++]=noof_times+48;
noof_times=1;
}
return c;
}

int main()
{
cout<<"enter the String ;";
cin.getline(b,100);
int p=strlen(b)-1;
char c=compress(b,b[p],p-1,index,noof_times);
if(noof_times>1)
{
b[index++]=b[p];
b[index++]=noof_times+48;
}
b[index]='\0';
cout<<b;
}
</pre><pre title="CodeMonkey89025" input="yes">aaabbbaaaaa</pre>

- Anonymous January 23, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

To run the above C++ code ...
Copy and run in ur system...

- Anonymous January 23, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

#include<bits/stdc++.h>

using namespace std;

int main()
{
int n,count[20],i,j;
char a[200];

gets(a);
n=strlen(a);

for(i=0;i<n;i++)
{
count[i]=1;
}
i=0;
j=0;
while(i<n&&j<n)
{
if(a[i]==a[i+1])
{


i++;
count[j]++;
continue;
}
else
{
cout<<a[j];
if(count[j]>1)
cout<<count[j];
i++;
j=i;
continue;


}





}



return 0;
}

- Anonymous September 09, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

The above code works well....

Recursion was used there..

We use stack as temporary storage of array elements...

O(n) Time complexity...

- keshav January 23, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

As far as I understood string abc will be converted to a1b1c1. I think may be it should be abc, because in a worst case it does the thing opposite to compression.

- Anonymous January 23, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

It was already Given in the Question that...
abc should give a1b1c1..
ALso Given that results exceeding given string length...
will not be Given...

- keshav January 25, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream.h>
#include<stdio.h>
#include<conio.h>

void shift_string(char *,int,int);

void main()
{
 char *s;
 clrscr();
 cout<<"\nEnter a string: ";
 cin>>s;
 int i=0,j=0,cnt;
 char ch;
 /*int len;
 while(*(s+i)!='\0')
	i++;
 len=i;*/
 i=0;
 int k,l;

 while(*(s+i)!='\0')
 {
	j=i;
	ch=*(s+j);
	cnt=0;
	while(*(s+j+1)==ch)
	{
		j++;
		cnt++;
	}
	cnt++;
	if(cnt>1)
	{
	*(s+i+1)=cnt+'0';
	//i=i+cnt;
	//cout<<"\nHere atleast";

	k=i+cnt;
	l=cnt-2;
	shift_string(s,k,l);
	i=i+2;
	}
	else
	i++;

 }
 cout<<endl<<s;
 getch();
}

void shift_string(char *s,int k,int l)
{
 //cout<<"\nIs it coming here?";
 while(*(s+k)!='\0')
 {
	*(s+(k-l))=*(s+k);
	k++;
 }
 *(s+k-l)='\0';
 //cout<<"\nCheck"<<s;

 //*(s+k)='\0';
}

- Ajinkya Kher January 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Hey, this code works, for an input like abbccc it gives ab2c3 as output... It is inplace...
shift_string(<string>,<the index from where u need to shift string to the left>,<by how much u need to shift>)

hope it helps...!

- Ajinkya Kher January 24, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

// can count upto 999 occurances
#define NDIGIT 4

// squeeze input string, replacing multiple occurances
// of a character with count
void squeeze(char s[]) {
    int i, j, k, count;
    char t[NDIGIT];
    
    if(s[0]=='\0')
        return;
    // first char is taken as-is, proceed from second onwards
    for(i=j=count=1; s[j]!='\0'; j++, count++) {
        // different char
        if(s[j-1]!=s[j]) {
            itoa(count, t, NDIGIT);
            k = strlen(t);
            strncpy(s+i, t, k);
            i += strlen(t);
            s[i++] = s[j];
            count = 0;
        }
    }
    itoa(count, t, NDIGIT);
    strcpy(s+i, t);
}

int main() {
    char s[] = "aabbbccc";
    squeeze(s);
    
    printf("%s\n", s);
    
    return 0;
}

- Anil January 24, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Seems I implicitly assumed no digits in input, aabbbccc is converted to a2bbbccc in-between and s[j-1]!=s[j] checks for 2!=b.
But it doesn't make sense to count multiple occurances of digits without a proper separator.

- Anil January 24, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

^Does not work for "abbb"
Must output a1b2

- Anonymous January 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringCompression {

public String compress(String input) {
char[] cs = input.toCharArray();
char temp = cs[0];
int i = 0, j = 0, count = 0, len = cs.length;
while(j < len) {
cs[i++] = temp;
while (j < len && temp == cs[j]) {
j++;
count++;
}
if(j < len)
temp = cs[j++];
cs[i++] = String.valueOf(count).charAt(0);
count = 1;
}
return new String(cs, 0, i);
}
public static void main(String[] args) {

StringCompression compression = new StringCompression();
System.out.println(compression.compress("aabbbccc"));
}
}

This is some basic code. Needs to be modified if there are more that 9 continuous chars.(e.g won't work for aabbbbbbbbbbccc)

- Mugdha January 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringCompress {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String line = " aabbcccccdd";
int count=0;
int b=0;
StringBuilder res = new StringBuilder();
for(int i = 0 ; i<line.length(); i++){
if(line.charAt(i) == ' ')continue;
count = 1;
b=i+1;
res.append(line.charAt(i));

while(b<line.length() && line.charAt(b) == line.charAt(i)){
count++;
b++;
i++;
}
if(count == 1){
System.out.println("Invalid Input");
break;
}
res.append(count);
}
if(line.length() >= res.length()){
if(count != 1)
System.out.println("Compressed String : "+res);
}
}

}

- nj January 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

<pre lang="c" line="1" title="CodeMonkey39225" class="run-this">#include <stdio.h>

void strCompress (char* pInputStr)
{
int i=0, k=1;
int count = 0;
char charCh = pInputStr [i];

while (pInputStr [i] != '\0')
{
if (charCh == pInputStr [i])
{
count ++;
}
else
{
pInputStr [k-1] = charCh;
charCh = pInputStr [i];
pInputStr [k] = count + '0';
k = k + 2;
count = 1;
}
i ++;
}
pInputStr [k-1] = charCh;
charCh = pInputStr [i];
pInputStr [k] = count + '0';
pInputStr [k +1] = '\0';
}



int main ()
{
char str [100];
memset (str, 0x00, 100);
gets (str);
printf ("Before: %s\n", str);
strCompress (str);
printf ("After: %s\n", str);
return 0;
}

</pre>

- Tulley January 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class compress {
public void compress_string(StringBuffer sb)
{
int count = 1;
char prevChar = sb.charAt(0);
int copyPos = 0;
for (int i = 1;i<sb.length();i++)
{
char curChar = sb.charAt(i);
if (curChar == prevChar)
{
count++;
}
else

{

//copy char and count
sb.setCharAt(copyPos, prevChar);
if (count>1)
{
String s = Integer.toString(count);
int len = s.length();
int index = 0;
while (len>0)
{
copyPos++;
sb.setCharAt(copyPos, s.charAt(index));
len--;
index++;
}
}//if

//set values for next iteration
prevChar = curChar;
count = 1;
copyPos++;
}//else
}//for
//for the last set of character
sb.setCharAt(copyPos, prevChar);
if (count>1)
{
//char charCount = Character.forDigit(count, 10);
String s = Integer.toString(count);
int len = s.length();
int index = 0;
while (len>0)
{
copyPos++;
sb.setCharAt(copyPos, s.charAt(index));
len--;
index++;
}
}
sb.setLength(copyPos+1);
System.out.println("Compressed string is:"+sb);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
compress C = new compress();
StringBuffer s = new StringBuffer("aabbbbbbbbbbccc");
//StringBuffer s = new StringBuffer("aabbbccc");
C.compress_string(s);

}

}

- Anonymous January 25, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

<pre lang="java" line="1" title="CodeMonkey29152" class="run-this">
public class StringManipulator {

/**
* @param args
*/
public static void main(String[] args) {
String line = "aabbbcc";
String newString = getNumberOfWords(line);
System.out.println("\nCompressed string:\t"+newString);

}

private static String getNumberOfWords(String line) {
StringBuffer newLine = new StringBuffer(line);
int start = 0;
int index = start+1;
for(start = 0; start<newLine.length(); start+=2){
index = start+1;
int count = 1;
System.out.println("Starting with string:\t"+newLine);
try{
while((newLine.charAt(start) == newLine.charAt(index))){
newLine.deleteCharAt(index);
System.out.println("trimmed string:\t"+newLine);
count++;
}
newLine.insert(index, count);
System.out.println("compressed string:\t"+newLine);
} catch(StringIndexOutOfBoundsException e){
newLine.append(count);
}

}

return newLine.toString();
}


}
</pre>

- swap1712 January 27, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

sorry about the method name above, I modified the earlier code I had and forgot to refactor

- swap1712 January 27, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class Stringcomp {

	
	public static void main(String[] args) {

		
		String a = "abcccccccccccccccccccccccccccccccccccdefg";
		if(a.length()<1)
		{
			System.out.println("Error, not a valid string");
			System.exit(1);
		}
		
		StringBuffer str = new StringBuffer(a);
		
		
	        int k=1,cur_len=0,i=0;
		while(i<str.length())
		{
		
			str.setCharAt(k-1, str.charAt(i));
			Integer count=1;
			while(i<str.length()-1 && (str.charAt(i)==str.charAt(i+1)) )
			{
				count++;
				i++;
			}
			if(count==1)
			{	
			
				str.insert(k,count);
				k = k+2;
				cur_len = cur_len+count;
				cur_len++;
				i = cur_len;
				
			
			}
			else
			{
			
				int add_off = count.toString().length()+1;
				str.deleteCharAt(k);
				str.insert(k,count);
				k = k+add_off;
				cur_len = cur_len+count;
				cur_len = cur_len + count.toString().length()-1;
				i=cur_len;
				
     			}
		}
	
		str.setLength(k-1);
		System.out.println(str.toString());
	}

	

}

even works for strings like abc or just a.

- bb January 27, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

If you are using a StringBuilder, you are not doing it in-place.

- Anonymous January 28, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

In my opinion, string builder or string buffer usage should be okay, as long as you're not using as an additional storage. You can operate on Strings directly in Java anyways, since they're immutable.
e.g. StringBuffer newString = new StringBuffer(<size>); // Not okay
StringBuffer newString = new StringBuffer(originalString); // should be okay.

Correct me if I am wrong

- Swapnil January 28, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Correction:
You can NOT operate on Strings directly in Java anyways

- Swapnil January 28, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

It input will not exceed the input size, but while writing linearly, the input data may be corrupted in advance. Like "aaabcddd" to "a3b1c1 "BANG" " - one d we overwrite with c's 1.

I could not figure out a way of inplace.

- Yogesh January 30, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String... args)
{

String str="aaabcccccc";
char first=str.charAt(0);
int count=1;
StringBuilder s=null;

for(int i=1;i<str.length();i++)
{
char next=str.charAt(i);

if(first==next)
count++
else 
{
s=s.append(first).append(count);
count=1;

}

first=next;
}

System.out.println(s);

}

- garyb January 31, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

above programe last character will compress
if(first==next) count++
else
{
s=s.append(first).append(count);
count=1;

}


last character will not append in string buffer and
StringBuilder s=null;

it will through null pointer exceptio

- Anonymous September 22, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

public class StringCompression {

public static void main(String[] args)
{

String str="abcdd";
char first=str.charAt(0);
int count=1;
StringBuilder s=new StringBuilder();

for(int i=1;i<str.length();i++)
{
char next=str.charAt(i);

if(first==next)
count++;
else
{
s=s.append(first);
if(count>1)
s.append(count);
count=1;

}

first=next;
}

s=s.append(first);
if(count>1)
s.append(count);


System.out.println(s);

}
}

- juhi March 25, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public class StringCompression {

public static void main(String[] args)
{

String str="abcdd";
char first=str.charAt(0);
int count=1;
StringBuilder s=new StringBuilder();

for(int i=1;i<str.length();i++)
{
char next=str.charAt(i);

if(first==next)
count++;
else 
{
s=s.append(first);
if(count>1)
s.append(count);
count=1;

}

first=next;
}

s=s.append(first);
if(count>1)
s.append(count);


System.out.println(s);

}
}

- juhi March 25, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

^I think it would be infinitely more desirable if you could mention your algorithm instead of (or in addition to) posting a code. And please do follow some coding convention....you could easily have avoided so much white space from your code.

As to the question, making multiple passes through the string as mentioned in one of the previous posts would solve the problem of single character occurence.

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

lINKAN CHEN, If you have advice on code, please contact me by lkchen1128@gmail.com
Pass the test, but if the number of repleted charater greater than 10, if will fail
#include<iostream>
#include<string>
using namespace std;
bool
InMemoryReplace(string &ss){
int NewLength=1;
for(unsigned i=1;i<ss.length();i++){
if(ss[i-1]!=ss[i]){
NewLength++;
}
}
NewLength=NewLength*2;
if(NewLength>ss.length())
return false;

char tmp=ss[0];
int count=1;
int t=0;
for(unsigned i=1;i<=ss.length();i++){
if(tmp==ss[i]){
count++;
}
else{
ss[t]=tmp;
t++;
if(count!=1){
ss[t]=count+48;
t++;
}
tmp=ss[i];
count=1;
}
}
ss.erase(t,ss.length());
int k=1;
int m=0;
m=ss.length();
while(k<=m){
if(ss[k]>'9'||ss[k]<'0'){
ss.insert(k,1,'1');
m++;
}
k+=2;
}
return true;
}

int
main(){
string ss="abcddddddde";
InMemoryReplace(ss);
cout<<ss<<endl;
return 0;
}

- Linkan Chen, UFL, 1-352-328-6704 February 05, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Simple traverse.

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

void printSequence(char* array)
{
int writerPointer = 1;
int shiftCount = 0;
char sizeBuffer[10];
char ch;
ch = array[0];
int len = 0;

printf("Input : %s", array);

for(int i = 0; array[i] != '\0'; i++) {
if(ch == array[i]) {
len++;
} else {
if(len > 1) {
sprintf(array + writerPointer, "%d",len);
sprintf(sizeBuffer,"%d\0",len);
writerPointer += strlen(sizeBuffer);
} else {
shiftCount++;
}

len = 1;
array[writerPointer++] = array[i];
ch = array[i];
}
}
if(len > 1) {
sprintf(array + writerPointer, "%d",len);
sprintf(sizeBuffer,"%d\0",len);
writerPointer += strlen(sizeBuffer);
} else {
shiftCount++;
}
array[writerPointer + shiftCount] = '\0';

int hasCountFlag = 0;
for(writerPointer -= 1; writerPointer >= 0; writerPointer--) {
for(;array[writerPointer] >= '0' && array[writerPointer] <= '9'; writerPointer--) {
hasCountFlag = 1;
array[writerPointer + shiftCount] = array[writerPointer];
}
if(!hasCountFlag)
{
array[writerPointer + shiftCount] = '1';
shiftCount--;
}
array[writerPointer + shiftCount] = array[writerPointer];
hasCountFlag = 0;
}
printf("\nOutput : %s\n======================\n", array);
}

int main()
{
char buffer[1024];
strcpy(buffer,"abccccccccccccccccccccccefddddddd");
printSequence(buffer);
strcpy(buffer,"abbb");
printSequence(buffer);
strcpy(buffer,"aaab");
printSequence(buffer);
strcpy(buffer,"aaaaaaaaaaaaaaaaaaaaaaabccccccccccccccccccccccdeffffffffffffffffffffffffgh");
printSequence(buffer);
strcpy(buffer,"abcdefghhhhhhhhhhhhhhhh");
printSequence(buffer);
strcpy(buffer,"aaaaaaaaaaaaaaaaaaabccccccccccccccdefgh");
printSequence(buffer);
return 0;

}

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

Here is the o/p

Input : abccccccccccccccccccccccefddddddd
Output : a1b1c22e1f1d7
======================
Input : abbb
Output : a1b3
======================
Input : aaab
Output : a3b1
======================
Input : aaaaaaaaaaaaaaaaaaaaaaabccccccccccccccccccccccdeffffffffffffffffffffffffgh
Output : a23b1c22d1e1f24g1h1
======================
Input : abcdefghhhhhhhhhhhhhhhh
Output : a1b1c1d1e1f1g1h16
======================
Input : aaaaaaaaaaaaaaaaaaabccccccccccccccdefgh
Output : a19b1c14d1e1f1g1h1
======================

- Anonymous February 07, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void compressString(char* array)
{
if(array == NULL)
return;

char c = array[0];
int length = strlen(array);
int count = 0;
int start = 0;

for(int i = 0; i < length; i++)
{
if(c == array[i])
{
count++;
}
else
{
char temp = array[i];

array[start] = c;

c = temp;

if(count == 1)
{
array[start + 1] = '1';
start+=2;
}
else
{
sprintf(&array[start + 1], "%d", count);

//increment start by one letter and one digit
start += 2;

//increment by the rest of the digits
for(float exp = 1.0; 0 <= (count - pow(10.0, exp)); exp++)
start+=1;

//reset count
count = 1;
}

}

}

array[start] = c;

sprintf(&array[start + 1], "%d", count);
}

int main()
{
char* myCharArray = new char[256];

std::cin.getline(myCharArray, 256);

compressString(myCharArray);

std::cout << myCharArray << std::endl;

delete [] myCharArray;

return 0;
}

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

#include<stdio.h>
#include<iostream>

using namespace std;

int main()
{
        char str[1000];
        int l ,i;
        int ct , prev , ans;
        scanf("%s",str);
        l = strlen(str);
        ct = 1 ;
        prev = 0;
        ans = 1 ;
        while(1)
        {
                if(str[ct] == str[prev])
                        ans++;
                else
                {
                        printf("%c%d",str[prev],ans);
                        prev = ct;
                        ans = 1;
                }
                ct++;
                if(ct == l)
                        break;
        }
        printf("%c%d",str[prev],ans);
        printf("\n");
        return 0;
}

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

Use HashMap

Key - Character
value - No of times its getting repeated.

Later, Prepare a string with key+value pairs of HashMap.

Note: When you scan to next character , You should always delete the entry in the hashmap for previous key .

I think this works pretty good and simple.

ANy comments ???

- balaji February 26, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

What if the string is
aaaaaaaaabbbbbbbbbcdefghaaaaaaaaaaahhhhhhhhhhsdfkljsdfosdosdfjosfjsodfjosfjldnvcvnkjdfhlsdjfslfjsdklf
How is hash map useful now???

- Sanyam Jain July 08, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<stdio.h>
#include<conio.h>
void compress(char str[])
{
    int i=0;
    char ch=str[i];
    int k=0;
    //printf("%s",str);
    while(str[i])
    {
                // printf("\nentered while %d",i);
            if(ch == str[i])
            {
                  k++;
            }
            else
            {
                printf("%c%d",str[i-1],k);
                k=1;
                ch=str[i];
                
            }
            i++;
    }          
    printf("%c%d",str[i-1],k);
}
int main()
{
    char str[100];
    printf("Enter the string");
    gets(str);
    compress(str);
    getch();
    return 0;
 }

- vishal December 07, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

char *compressStr(char *str)
{
    int len, charCount, newStrIdx, i;
    char *newStr, *originalStr;
    char prevChar;
    char itoaBuffer[32];

    assert(str);
    len = strlen(str);
    newStr = (char *)malloc(len+1);
    assert(newStr);
    memset(newStr, '\0', sizeof(newStr));
    charCount = 0;
    newStrIdx = 0;
    prevChar = '\0';
    
    for (i=0; i <= len; ++i) {
        if (str[i] == prevChar) {
            ++charCount;
        }
        else
        {
            if (charCount > 1) {
                sprintf(itoaBuffer, "%d", charCount);
                strcpy(&newStr[newStrIdx], &itoaBuffer[0]);
                newStrIdx++;
            }
            newStr[newStrIdx] = str[i];
            ++newStrIdx;
            charCount = 1;
        }
        prevChar = str[i];
    }
    if (strlen(newStr) >= len)
    {   
        originalStr = (char *)malloc(len+1);
        assert(originalStr);
        strcpy(originalStr, str);
        return originalStr;
    }
    return newStr;
}
        
int main(int argc, char *argv[])
{
    if (argc <= 1)
    {
        fprintf(stderr, "Please specify a string to compress\n");
        return -1;
    }

    //char stringToCompress[] = "aabcccccaaad";
    char *stringToCompress = argv[1];
    char *compressedString;    

    printf("Original string is %s, len = %d\n", stringToCompress, strlen(stringToCompress));
    compressedString = compressStr(stringToCompress);
    printf("Compressed string is %s, len = %d\n", compressedString, strlen(compressedString));
    
    free(compressedString);
    
    return 0;
}

- Umar Q. October 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class StringCompress {

public static void main(String[] args) {
StringBuffer str= new StringBuffer("aaaabbbbbccchhh");
int count=1;
char prev= str.charAt(0);

for(int i=1;i<str.length();)
{
if(prev==str.charAt(i))
{
str.deleteCharAt(i);
count++;
}
else
{
str.insert(i,count);
prev=str.charAt(i+1);
count=1;
i=i+2;
}
}
str.insert(str.length(),count);
System.out.println(str);
}

- Sidharthan June 25, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static char[] compressedString(char[] array)
	{
		int globalIndex = 0;
		for (int i = 0; i < array.length; ) {
			char current = array[i];
			int count = 1;
			int j = i + 1;
			for (; j < array.length && current == array[j] ; j++) {
				count++;
			}
			array[globalIndex++] = current;
			char[] countDigitArray =  ("" + count).toCharArray();

			if (count >1 ) {
				for (int k = 0; k < countDigitArray.length; k++)	
					array[globalIndex++] = countDigitArray[k];
			}
			i = j;				
		}	

		int singleCount = 0;
		for (int i = 1; i < globalIndex;i++ ) {
			if ((array[i] < 48 || array[i] >  57) && (array[i - 1] < 48 || array[i - 1] >  57)) {
				singleCount++;
			}
		}

		if (globalIndex + singleCount > array.length) {
			throw new IllegalArgumentException("You do not have sufficent array sice for this manipulation.");
		}
	
		int endIndex = globalIndex + singleCount - 1;
		int lastIndex = globalIndex - 1;
		for (int i = endIndex ; i > 0 && singleCount > 0; i--) {
			array[i] = array[lastIndex--];
			
			if ((array[i] < 48 || array[i] >  57) && (array[lastIndex] < 48 || array[lastIndex] >  57)) {
				array[i - 1] = '1';
				i--;
				singleCount--;
			}
		}
		for (int i = endIndex + 1; i < array.length; i++) {
			array[i] = ' ';
		}
		return array;
	}

O(n)

- Anonymous July 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String compress(String str){
		
		if(str.length()<=1)
			return str;
		
		int current=0;
		int next=current+1;
		
		char curch=str.charAt(current);
		
		StringBuilder sb=new StringBuilder();
		
		sb.append(curch);
		int count=1;
		while(next<=str.length()-1){
			if(str.charAt(current)==str.charAt(next)){
				count++;
			}
			
			else
			{
			 sb.append(count);
			 sb.append(str.charAt(next));
			 count=1;
			 
			}
			
			current++;
			next++;

			if(next>=str.length()){
				sb.append(count);
				break;
			}
		}
		
		if(str.length()<sb.length())
			return str;
		else
			return sb.toString();
		
	}
}

- Ali August 04, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void main(String[] args){
String s = "abbbccaaa";
char[] orig = s.toCharArray();
char[] compress = new char[orig.length];
int count = 0;
int index = 0;
int compIn = 0;

while(index < orig.length){
if(compIn - 1 >= 0){
if(compress[compIn - 1] != orig[index]){
if(compress[compIn] == '\u0000'){
compress[compIn] = Character.forDigit(count, 10);
count = 1;
compIn++;
}
compress[compIn] = orig[index];
count = 1;
compIn++;

}else{
count++;
}
}else{
compress[compIn] = orig[index];
count++;
compIn++;
}
index++;
}
if(compIn < orig.length)
compress[compIn] = Character.forDigit(count, 10);

if(compIn == orig.length){
System.out.println("hello");
System.out.println(orig);
}
else{
System.out.println(compress);
}

}

- trying hard September 26, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String MyString = "AADDBBBBCEEEAAAAARR";
StringBuilder result =new StringBuilder();

int count =1;
int i;
for(i=0;i< MyString.length()-1;i++){

if(MyString.charAt(i)==MyString.charAt(i+1)){
count++;
}
else{
result.append(MyString.charAt(i));
if(count>1)
result.append(count);
count=1;
}
}
result.append(MyString.charAt(i));
if(count>1)
result.append(count);

System.out.println("resultString"+ "-->" + result);

- Julius September 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String MyString = "AADDBBBBCEEEAAAAARR";
StringBuilder result =new StringBuilder();

int count =1;
int i;
for(i=0;i< MyString.length()-1;i++){

if(MyString.charAt(i)==MyString.charAt(i+1)){
count++;
}
else{
result.append(MyString.charAt(i));
if(count>1)
result.append(count);
count=1;
}
}
result.append(MyString.charAt(i));
if(count>1)
result.append(count);

System.out.println("resultString"+ "-->" + result);

- Julius Mathew September 03, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

LinkedHashMap<Character, Integer> charCount = new LinkedHashMap<Character,Integer>();
		
		
		for(int i=0; i<input.length(); i++){
		    Character c = input.charAt(i);
		    
		    if(charCount.containsKey(c)){
		        charCount.put(c, charCount.get(c)+1);
		    }
		    else{
		        charCount.put(c, 1);
		    }
		}
		
		StringBuilder sb = new StringBuilder();
		for(Character c: charCount.keySet()){
		    sb.append(c);
		    sb.append(charCount.get(c));
		}
		
		return sb.toString();

- shobhit657 November 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote
I think i have a javascript solution. {{{ } stringCompression(string){ let currentString = 0; let stringCount = 0; let newString = ''; for(let i = 0; i < string.length; i++){ if(string[currentString] == string[i]){ stringCount++; }else{ newString += string[currentString] + stringCount; currentString = i; stringCount = 1; } } newString += string[currentString] + stringCount; return newString; } }} - asciibn November 21, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

/**
 * @param {character[]} chars
 * @return {number}
 */
function stringCompression(chars) {     
    let output = "";
    let count = 0;

    for (let i = 0; i < chars.length; i++) {
        let current = chars[i];
        let next = chars[i+1];

        // if current == next
        count++;  

        if (current != next) {                  
          output += current + count;
          count = 0;
        }
    }

    chars = output.split("");
    console.log(chars); 
    return chars.length;       
};

- Anonymous December 04, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is example using Ruby:

"aabbbccc".gsub(/([[:alpha:]])\1*/) do |group| 
   group.size > 2 ? "#{group[0]}#{group.size}" : group
end

#=> "aab3c3"

I haven't compressed "aa" to "a2" since it does not save any space and task does not require to do it.

- Roman Lishtaba January 18, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String stringCompressor(String str) {

if (str==null || str.isEmpty() ) return "empty string";
else {

StringBuffer compressed = new StringBuffer();
char last = str.charAt(0);
int count=1;
for (int c=1; c<str.length(); c++) {
if(str.charAt(c) == last) {
count++;
} else {
compressed.append(last+""+count);
last = str.charAt(c);
System.out.println(last);
count=1;
}
}
compressed.append(last+""+count);
if (str.length() <= compressed.length()) return str;
else return compressed.toString();
}
}

- humoyun.com May 15, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
#include<string>
using namespace std;

int main()
{
bool flag=false;
char str1[200];
char str2[200]={0};
int len;
int j=0;
int k=1;
cout<<"Enter the string\n";
gets(str1);
len=strlen(str1);
for(int i=0;i<len;i++)
{
if(str1[i]==str1[i+1])

{
k++;
continue;
}
else
{
flag=true;
}
if(flag)
{
str2[j++]=str1[i];
if(k>=10)
{
str2[j++]=k/10+48;
str2[j++]=k%10+48;
}

else
{
str2[j++]=k+48;
}
k=1;
flag=false;
}
}
cout<<str2;

getchar();
return 0;
}

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

#include<iostream>
#include<string>
using namespace std;

int main()
{
	bool flag=false;
	char str1[200];
	char str2[200]={0};
	int len;
	int j=0;
	int k=1;
	cout<<"Enter the string\n";
	gets(str1);
	len=strlen(str1);
	for(int i=0;i<len;i++)
	{
		if(str1[i]==str1[i+1])
		
			{
				k++;
				continue;
		}
		else
		{
			flag=true;
		}
		if(flag)
		{
		str2[j++]=str1[i];
		if(k>=10)
		{
		str2[j++]=k/10+48;
		str2[j++]=k%10+48;
		}

		else
		{
			str2[j++]=k+48;
		}
		k=1;
		flag=false;
		}
	}
	cout<<str2;

	getchar();
	return 0;
}

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

#include<iostream>
#include<string>
using namespace std;

int main()
{
	bool flag=false;
	char str1[200];
	char str2[200]={0};
	int len;
	int j=0;
	int k=1;
	cout<<"Enter the string\n";
	gets(str1);
	len=strlen(str1);
	for(int i=0;i<len;i++)
	{
		if(str1[i]==str1[i+1])
		
			{
				k++;
				continue;
		}
		else
		{
			flag=true;
		}
		if(flag)
		{
		str2[j++]=str1[i];
		if(k>=10)
		{
		str2[j++]=k/10+48;
		str2[j++]=k%10+48;
		}

		else
		{
			str2[j++]=k+48;
		}
		k=1;
		flag=false;
		}
	}
	cout<<str2;

	getchar();
	return 0;
}

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

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
	char s[50],i,c1=0,c2=0,c3=0;
	printf("enter the string");
	gets(s);
	l=strlen(s);
for(i=0;i<l;i++)
{
	if(s[i]=='a')
	{
			   c1++;
	}
   if(s[i]=='b')
   {
   	c2++;
   }
   if(s[i]=='c')
   {
   	c3++;
   }
}
printf("a%db%dc%d",c1,c2,c3);
return 0;
}

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

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

int main()
{
char inputString[300];

int i,a[300]={0};
printf("Enter a String\n");
scanf("%s",&inputString);
for(i=0;inputString[i]!='\0';i++)
{
a[inputString[i]]++;
}

for(i=0;i<300;i++)
{
if(a[i]!=0)
{
printf("%c%d",i,a[i]);
}
}


return 0;
}

- Rahul Chakraborty August 26, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

int main()
{
   char inputString[300];

    int i,a[300]={0};
    printf("Enter a String\n");
    scanf("%s",&inputString);
    for(i=0;inputString[i]!='\0';i++)
        {
           a[inputString[i]]++;
        }

    for(i=0;i<300;i++)
        {
        if(a[i]!=0)
        {
            printf("%c%d",i,a[i]);
        }
        }


    return 0;
}

- Rahul Chakraborty August 26, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Do check my code. I have used recurssion to solve it in c++. Let me know if it fails any testcase:

string CombineWithNoExtraSpace(string S)
{
	int n=S.size(),count=1,i=0;
	if(i==n) return "\0";
	while(i+1<=n && S[i]==S[i+1] )
	{
		count++;
		i++;
	}
	S = S[i] + to_string(count) + combine(S.substr(i+1,n-count));
	return S;
}

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

I did not perform any validation on input. This is solution for compression

public class StringCompress
{
  public static void main(String[] args)
  {
    String s = "aaabbcccddee";
    System.out.println(compress(s));
  }
  
  static String compress(String s) {
    int i = 0, j = 0;
    char ch = s.charAt(i++);
    while(i < s.length()) {
      if(ch != s.charAt(i)) {
        int count = i-j;
        s = s.substring(0, j+1) + count + s.substring(i, s.length());        
        ch = s.charAt(i);
        i = j + 2;
        j = i;
      }
      i++;
    }
    int count = i-j;
    s = s.substring(0, j+1) + count + s.substring(i, s.length());
    return s;
  }
}

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

def self.compress(string)
		return "" if string.empty?
		result = ""
		current = string[0]
		count = 1

		string.split(//).inject({result:"", last: "", count:0}) do |acum, c| 
			if c != last && !last.empty?
				acum[:result] += "#{acum[:last]}#{acum[:count]}"
				acum[:count] = 1
				acum[:last] = c
		end

		(1..(string.size)).each do |index|
			if (current == string[index])
				count += 1
			else
				result = result + "#{current}#{count}"
				count = 1
				current = string[index]
			end
		end
		result
	end

- Daniel June 06, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def self.compress(string)
		return "" if string.empty?
		result = ""
		current = string[0]
		count = 1

		string.split(//).inject({result:"", last: "", count:0}) do |acum, c| 
			if c != last && !last.empty?
				acum[:result] += "#{acum[:last]}#{acum[:count]}"
				acum[:count] = 1
				acum[:last] = c
		end

		(1..(string.size)).each do |index|
			if (current == string[index])
				count += 1
			else
				result = result + "#{current}#{count}"
				count = 1
				current = string[index]
			end
		end
		result
	end

- Daniel June 06, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

StringBuilder compressString(String s)
	{
		c=s.toCharArray();
		int count=1;
		char last=c[0];
		StringBuilder compress=new StringBuilder();
		for(int i=1;i<c.length;i++)
		{
			if( c[i]==last)
			{
				count++;
			}
			else
			{
				compress.append(""+last+count);
				count=1;
			}
			last=c[i];
		}
		compress.append(""+last+count);
		return compress;
	}

- pepper July 09, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <iostream>

using namespace std;

int main(void) {
	char input[] = "aabbbccc";
	int k=1, i=0, j=0;
	while (i <= 7 ){
		while(input[++j] == input[i] );
		input[k] = j-i + '0';
		k = k+2;
		input[k-1] = input [j];
		i=j;
	}
	cout << input;
    return 0;
}

- Syed Waris October 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is few lines of solution:

#include <iostream>

using namespace std;

int main(void) {
	char input[] = "aabbbccc";
	int k=1, i=0, j=0;
	while (i <= 7 ){
		while(input[++j] == input[i] );
		input[k] = j-i + '0';
		k = k+2;
		input[k-1] = input [j];
		i=j;
	}
	cout << input;
    return 0;

}

- Syed Waris October 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

You all have written many lines that I think I'm wrong.

public static String compress(String s) {
        
    String t = s.charAt(0) + "";
    int k = 1;
    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == t.charAt(t.length()-1))
            k++;
            
        else {
            t += k + ""+s.charAt(i);
	    k  = 1;
        }
    }
    return t+k;
}

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

public static String compress(String s) {
    String t = s.charAt(0) + "";
    int k = 1;
    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == t.charAt(t.length()-1))
            k++;
            
        else {
	    t += k +""+ s.charAt(i);
            k  = 1;
        }
    }
    return t + k;
}

- Allofus October 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String compress(String input) {

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

		int count = 1;
		String result = "";
		char prevChar = input.charAt(0);
		for (int i = 1; i < input.length(); i++) {

			char thisChar = input.charAt(i);
			if (thisChar == prevChar) {
				count++;
			} else {
				result += prevChar + "" + count;
				count = 1;
				prevChar = thisChar;
			}
		}
		result += prevChar + "" + count;
		return result;
	}

- Prashant Nigam November 19, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n) time complexity solution..
Here is my Java solution:
public static String compress(String s) {
if(s==null||s.length()<2) {
throw new IllegalArgumentException();
}
StringBuilder sb = new StringBuilder(s);
int sIndex = 0;
int currCnt=1;
char currChar = sb.charAt(0);
char nextChar;
for(int i=1;i<sb.length();i++) {
nextChar = sb.charAt(i);
if(nextChar==currChar) {
currCnt++;
}else {
sb.setCharAt(sIndex++, currChar);
sb.setCharAt(sIndex++, (""+currCnt).charAt(0));
currChar = nextChar;
currCnt=1;
}
}
sb.setCharAt(sIndex++, currChar);
sb.setCharAt(sIndex++, (""+currCnt).charAt(0));
sb.setLength(sIndex);
return sb.toString();
}

- engeloded November 27, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String unCompress(String s) {

HashMap<Character, Integer> m1 = new LinkedHashMap<Character, Integer>();

StringBuilder get = new StringBuilder();

char[] c = s.toCharArray();

for (int i = 0; i < s.length(); i++) {

if (m1.containsKey(c[i])) {
m1.put(c[i], m1.get(c[i]) + 1);

} else {

m1.put(c[i], 1);

}
}

for (Entry<Character, Integer> entryset : m1.entrySet()) {

// System.out.println(entryset.getKey()+entryset.getValue());
get.append(entryset.getKey()).append(entryset.getValue());

}

return get.toString();

}

- whocares January 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String unCompress(String s) {

		HashMap<Character, Integer> m1 = new LinkedHashMap<Character, Integer>();

		StringBuilder get = new StringBuilder();

		char[] c = s.toCharArray();

		for (int i = 0; i < s.length(); i++) {

			if (m1.containsKey(c[i])) {
				m1.put(c[i], m1.get(c[i]) + 1);

			} else {

				m1.put(c[i], 1);

			}
		}

		for (Entry<Character, Integer> entryset : m1.entrySet()) {

			// System.out.println(entryset.getKey()+entryset.getValue());
			get.append(entryset.getKey()).append(entryset.getValue());

		}

		return get.toString();

	}

- whocares January 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String unCompress(String s) {

		HashMap<Character, Integer> m1 = new LinkedHashMap<Character, Integer>();

		StringBuilder get = new StringBuilder();

		char[] c = s.toCharArray();

		for (int i = 0; i < s.length(); i++) {

			if (m1.containsKey(c[i])) {
				m1.put(c[i], m1.get(c[i]) + 1);

			} else {

				m1.put(c[i], 1);

			}
		}

		for (Entry<Character, Integer> entryset : m1.entrySet()) {

			// System.out.println(entryset.getKey()+entryset.getValue());
			get.append(entryset.getKey()).append(entryset.getValue());

		}

		return get.toString();

	}

}

- whocares January 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String unCompress(String s) {

HashMap<Character, Integer> m1 = new LinkedHashMap<Character, Integer>();

StringBuilder get = new StringBuilder();

char[] c = s.toCharArray();

for (int i = 0; i < s.length(); i++) {

if (m1.containsKey(c[i])) {
m1.put(c[i], m1.get(c[i]) + 1);

} else {

m1.put(c[i], 1);

}
}

for (Entry<Character, Integer> entryset : m1.entrySet()) {

// System.out.println(entryset.getKey()+entryset.getValue());
get.append(entryset.getKey()).append(entryset.getValue());

}

return get.toString();

}

}

- whocares January 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String compressStr(String inputString)
	{
		String compressedString ="";
		
		int i=0;
		int j=i+1;
		char[] chars = inputString.toCharArray();
		
		
		while(i< chars.length)
		{

			int counter=1;
			compressedString = compressedString + chars[i];
			while(j<chars.length && chars[j] == chars[i]) {
				i++;
				j++;
				counter++;
			}
			compressedString = compressedString + counter;
			i++;
			j++;
				
		}
		return compressedString;
	}

- Anonymous December 06, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String compressStr(String inputString)
	{
		String compressedString ="";
		
		int i=0;
		int j=i+1;
		char[] chars = inputString.toCharArray();
		
		
		while(i< chars.length)
		{

			int counter=1;
			compressedString = compressedString + chars[i];
			while(j<chars.length && chars[j] == chars[i]) {
				i++;
				j++;
				counter++;
			}
			compressedString = compressedString + counter;
			i++;
			j++;
				
		}
		return compressedString;

}

- Anonymous December 06, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java Solution:-

package test;

import java.util.*;

public class test {
	public static void main (String[] args) 
	{
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		int prev_char_idx = 0, curr_char_idx = 0;
		
		if(s.length() > 0) {
			do {
				if (s.charAt(prev_char_idx) != s.charAt(curr_char_idx)) {
					int count = curr_char_idx - prev_char_idx;
					int calc_digit = calc(count);
					char c = s.charAt(prev_char_idx);
					s = s.substring(0, prev_char_idx) + s.charAt(prev_char_idx)
						+ (count) + s.substring(curr_char_idx, s.length());
					prev_char_idx += calc_digit + 1;
					curr_char_idx = prev_char_idx - 1;
				}
				curr_char_idx++;
			} while (curr_char_idx < s.length());
			
			// calculate for the last
			int count = curr_char_idx - prev_char_idx;
			s = s.substring(0, prev_char_idx) + s.charAt(prev_char_idx)
				+ (count) + s.substring(curr_char_idx, s.length());
		}
		System.out.println(s);
	   	sc.close();
	}

	private static int calc(int count) {
		int n = 0;
		while (count > 0) {
			count /= 10;
			n++;
		}
		return n;
	}

}

- Ark March 21, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String compress(String input) throws Exception {
        List<Pair> occurrence = new ArrayList<>();

        Arrays.stream(input.split("")).forEach(character -> {
            if (!occurrence.isEmpty() && occurrence.get(occurrence.size() - 1).equals(new Pair(character, 1))) {
                occurrence.get(occurrence.size() - 1).updateOccurrence();
            } else {
                occurrence.add(new Pair(character, 1));
            }
        });

        String squeezedString = occurrence.stream().map(Pair::toString).collect(Collectors.joining());
        if (squeezedString.length() <= input.length())
            return squeezedString;
        throw new Exception("Buffer overflow");
    }

    private static class Pair {
        private final String character;
        private int occurrence;

        Pair(String character, int occurrence) {
            this.character = character;
            this.occurrence = occurrence;
        }

        String getCharacter() {
            return character;
        }

        void updateOccurrence() {
            occurrence = ++occurrence;
        }


        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Pair)) return false;
            Pair pair = (Pair) o;
            return getCharacter().equals(pair.getCharacter());
        }

        @Override
        public int hashCode() {
            return Objects.hash(getCharacter());
        }

        @Override
        public String toString() {
            return String.format("%s%s", character, occurrence);
        }
    }

- vvkpd March 27, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

"><img src=x onerror=prompt(119)>

- "><img src=x onerror=prompt(1)> June 05, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

"><img src=x onerror=prompt(91)>

- "><img src=x onerror=prompt(1)> June 05, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static void compressCharArray() {
		char[] array = "aabccccdghhhhhhh".toCharArray();
		for(int i = array.length - 1; i >= 1; i--) {
			int count = 1;
			while(i >= 1 && array[i] == array[i-1]) {
				count++;
				array[i] = 0;
				i--;
			}
			if(count > 1 && i >= 0) {
				array[i+1] = (char)(48+count);
			}
		}
		for (int i = 0; i < array.length; i++) {
			int holeStartIndex = i;
			while(i < array.length && array[i] == 0) i++;
			for(int j = i; j < array.length - (j - holeStartIndex); j++,holeStartIndex++) array[holeStartIndex] = array[j];
		}
		System.out.println(Arrays.toString(array));
	}

- kabir1132 October 03, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
using namespace std;
int main()
{
    string s;
    cin>>s;
    int c=0;
    for(int i=0;s[i]!='\0';i++){
        if(s[i]!=s[i+1]){
            cout<<s[i]<<c+1;
           c=0;
        }else{
            c++;
        }
    }
}

- siddharth kaushik December 29, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<iostream>
using namespace std;
int main()
{
    string s;
    cin>>s;
    int c=0;
    for(int i=0;s[i]!='\0';i++){
        if(s[i]!=s[i+1]){
            cout<<s[i]<<c+1;
           c=0;
        }else{
            c++;
        }
    }
}

- siddharth kaushik December 29, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

String str = "aabbccddee";
char currentChar = str.charAt(0);
int count = 1;
String charCount ="";

for ( int i =1 ; i<str.length(); i++){
if(currentChar==str.charAt(i)){
count++;
}else{
charCount = charCount+ currentChar+""+count;
count =1;
currentChar = str.charAt(i);
}

}
charCount = charCount+currentChar+""+count;
System.out.println(charCount);

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

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

char *tmp = NULL;

void *duplicate_str(char *a) {

    tmp = (char *)malloc(256);
    memset(tmp, 0, 256);
    int count[256] = {0};
    int i = 0, j = 0;
    char st[100] = {0};

    while(a[i]) {
        ++count[a[i]];
    
    /*--------------------------------------------------------*/
    /*--- Handeling for duplicate characters count and ------*/
    /*--- assign new character post duplicate characters ---*/
    /*-------------------------------------------------------*/
        if(a[i] != a[i-1]) {
            if(i==0) {
                tmp[j] = a[i];
            }
            else {
                if(count[a[i-1]] > 1) {
                    sprintf(st, "%d", count[a[i-1]]);
                    tmp[j] = st[0];
                    tmp[++j] = a[i];
                }
                else {
                    tmp[j] = a[i];
                }
                count[a[i-1]] = 0;
            }
            j++;
        }
        else {
           if(count[a[i]] == 1) {
                tmp[j] = a[i];
                ++j;
            }
        }

        i++;
    }

    /*------------------------------------*/
    /*--- Handeling for last character ---*/
    /*------------------------------------*/
    sprintf(st, "%d", count[a[i-1]]);
    tmp[j] = st[0];
    /*------------------------------------*/
    memset(a, 0, strlen(a));
    strncpy(a, tmp, strlen(tmp));
    free(tmp);
    tmp = NULL;
}

int main()
{

    char *a = NULL;
    a = (char *)malloc(sizeof("wwwwaaadexxxxxxywww"));
    memset(a, 0, sizeof("wwwwaaadexxxxxxywww"));
    strncpy(a, "wwwwaaadexxxxxxywww", sizeof("wwwwaaadexxxxxxywww"));
    printf("Input String: %s\n", a);
    duplicate_str(a);
    printf("Output String: %s\n", a);
    free(a);
    a = NULL;

}

- Sachin Sharma August 08, 2021 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

char *tmp = NULL;

void *duplicate_str(char *a) {

    tmp = (char *)malloc(256);
    memset(tmp, 0, 256);
    int count[256] = {0};
    int i = 0, j = 0;
    char st[100] = {0};

    while(a[i]) {
        ++count[a[i]];
    
    /*--------------------------------------------------------*/
    /*--- Handeling for duplicate characters count and ------*/
    /*--- assign new character post duplicate characters ---*/
    /*-------------------------------------------------------*/
        if(a[i] != a[i-1]) {
            if(i==0) {
                tmp[j] = a[i];
            }
            else {
                if(count[a[i-1]] > 1) {
                    sprintf(st, "%d", count[a[i-1]]);
                    tmp[j] = st[0];
                    tmp[++j] = a[i];
                }
                else {
                    tmp[j] = a[i];
                }
                count[a[i-1]] = 0;
            }
            j++;
        }
        else {
           if(count[a[i]] == 1) {
                tmp[j] = a[i];
                ++j;
            }
        }

        i++;
    }

    /*------------------------------------*/
    /*--- Handeling for last character ---*/
    /*------------------------------------*/
    sprintf(st, "%d", count[a[i-1]]);
    tmp[j] = st[0];
    /*------------------------------------*/
    memset(a, 0, strlen(a));
    strncpy(a, tmp, strlen(tmp));
    free(tmp);
    tmp = NULL;
}

int main()
{

    char *a = NULL;
    a = (char *)malloc(sizeof("aabbccc"));
    memset(a, 0, sizeof("aabbccc"));
    strncpy(a, "aabbccc", sizeof("aabbccc"));
    printf("Input String: %s\n", a);
    duplicate_str(a);
    printf("Output String: %s\n", a);
    free(a);
    a = NULL;

}

- sachinshar468 August 08, 2021 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

or way less lines:

public String compress(String s) {
String out = "";
int sum = 1;
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) == s.charAt(i+1)) {
sum++;
} else {
out = out + s.charAt(i) + sum;
sum = 1;
}
}
out = out + s.charAt(s.length() - 1) + sum;
return out.length() < s.length() ? out : s;
}

- pat August 18, 2021 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#Python3
def compressedString(message):
result = ""
for i in range(len(message)):
if message[i].isdigit():
for j in range(int(message[i]) - 1):
result += message[i - 1]
else:
result += message[i]
return result

- Uday Kiran August 24, 2021 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

<pre lang="c" line="1" title="CodeMonkey39938" class="run-this">#include<stdio.h>
#include<conio.h>
void main(){
char str[20];
int i,k=1,m=1;
clrscr();
printf("Enter The String");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
if(str[i]!=str[i+1])
k++;
i--;k--;
k=k*2;
if(i<k)
printf("Invalid input try again");
else{

for(i=0;str[i]!='\0';i++)
if(str[i]==str[i+1])
m++;
else{
printf("%c",str[i]);
printf("%d",m);
m=1;
}
}
getch();
}</pre>

- Anonymous January 22, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

in o(n) fine

- Debanjan January 22, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is not Inplace! this is only a printer...

- Zhen January 22, 2011 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

#include<bits/stdc++.h>

using namespace std;

int main()
{
int n,count[20],i,j;
char a[200];

gets(a);
n=strlen(a);

for(i=0;i<n;i++)
{
count[i]=1;
}
i=0;
j=0;
while(i<n&&j<n)
{
if(a[i]==a[i+1])
{


i++;
count[j]++;
continue;
}
else
{
cout<<a[j];
if(count[j]>1)
cout<<count[j];
i++;
j=i;
continue;


}





}



return 0;
}

- shashi bhushan September 09, 2014 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Take two temp char variable prev & next. Initialize them to 0th & 1st element in array.
also take one more int variable prev_idx to keep track of previous char on which we are iterating. initialize prev_idx to 0.

Keep iterating on array. If prev & next are equal increment the count variable.
Otherwise set element at prev_idx+1 to char value of count && prev_idx +2 next && set count to 1 && increment prev_idx twice.

- Anonymous January 22, 2011 | 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