Bloomberg LP Interview Question for Software Engineer / Developers


Country: United States
Interview Type: Written Test




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

public String calculateRun(String s) {
	char runChar = s.chartAt(0);
	int maxRun = 1;
	int currentRun = 1;
	for (int i = 1; i < s.length(); i++) {
		if (s.charAt(i) != s.charAt(i-1)) {
			if (currentRun > maxRun) {
				runChar = s.charAt(i-1);
				maxRun = currentRun;
			}
			currentRun = 1;
		} else {
			currentRun++;
		}
	}
	if (currentRun > maxRun) {
		runChar = s.charAt(i-1);
		maxRun = currentRun;
	}

	StringBuilder res = new StringBuilder();
	for (int i = 0; i < maxRun; i++) {
		res.append(runChar);
	}
	return res.toString();
}

- Anonymous March 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 votes

Perfect!

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

It is good and efficient, O(N), but at line 17, there is no variable called 'i' because it was only available in the for() loop and destroyed after leaving the context of the for loop. I think the "int i=1" should be put before the for.

- Anonymous August 15, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

import java.util.*;
public class Maxpattern{
    
    
    public static Map findmaxpattern(String str){
        Map map = new TreeMap();
        for(int i=0;i<str.length();i++){
             int count =1;
            if(map.containsKey(str.charAt(i))){
                count = (int)map.get(str.charAt(i))+1;
                map.put(str.charAt(i),count);
            }else{
                map.put(str.charAt(i),count);
            }
        }
        return map;
    }
    
    public static void main(String [] args){
        Map<String,Integer> list = findmaxpattern("aabbbbbbbbbcccdddddddddd");
        int max=0;
        for (Map.Entry<String,Integer> entry : list.entrySet()) {
        {
        	if(entry.getValue()>max){
        		max=entry.getValue();
        	}
        }
    }
        System.out.println("Maximum number of occurrence: "+max);
        
}

}

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

import java.util.*;
public class Maxpattern{
    
    
    public static Map findmaxpattern(String str){
        Map map = new TreeMap();
        for(int i=0;i<str.length();i++){
             int count =1;
            if(map.containsKey(str.charAt(i))){
                count = (int)map.get(str.charAt(i))+1;
                map.put(str.charAt(i),count);
            }else{
                map.put(str.charAt(i),count);
            }
        }
        return map;
    }
    
    public static void main(String [] args){
        Map<String,Integer> list = findmaxpattern("aabbbbbbbbbcccdddddddddd");
        int max=0;
        for (Map.Entry<String,Integer> entry : list.entrySet()) {
        {
        	if(entry.getValue()>max){
        		max=entry.getValue();
        	}
        }
    }
        System.out.println("Maximum number of occurrence: "+max);
        
}

}

- Sudheer January 01, 2016 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

public static void run(String str)
	{
		char runChar = str.charAt(0);
		String result = "";
		int currentRun = 1;
		int maxRun = 1;
		int i=0;
		for( i=1;i<str.length();i++)
		{
			if(str.charAt(i) == str.charAt(i-1))
			{
				currentRun++;
				if(currentRun > maxRun)
				{
					maxRun = currentRun;
					runChar = str.charAt(i-1);
				}
			}
			else
			{
				currentRun = 1;
			}
		}
		for(i=0;i<maxRun;i++)
		{
			result = result+runChar;
		}
		System.out.println(maxRun);
		System.out.println(result);

}

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

if(str.length < 1 ) //rubbish;

char c=str[0]; //character of current run
char max_c=c; //character of maximum run

int pos=0; //position (index) of beginning of current run
int max_run=1; //length of maximum run

for(int i=1; i<str.length; i++)
{
	if(str[i] != c) {  //we've exited a run
		if(i-pos > max_run) max_run=i-pos, max_c=c;  //update max info if needed

	 c=str[i], pos=i;  //regardless, mark the start of new run
}

for(int i=0; i<max_run; i++) putchar(max_c);

- S O U N D W A V E March 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

It's efficient but not correct.
For example if the string 'str' end with the longest sequence, it wouldn't notice it. E.g.: for str = "aabbbb"; it would give "aa" instead of "bbbb".

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

Using Hashmap ---> time complexity is O(n)

private static String getCharRUn(String str)
{
         
         Map<Character, Integer> charMap = new LinkedHashMap<Character, Integer>();
         
         for(int i = 0; i < str.length(); i++)
         {
             if(charMap.containsKey(str.charAt(i)) == false)
             {
                 charMap.put(str.charAt(i), 1);
             }
             else
             {
                 charMap.put(str.charAt(i), charMap.get(str.charAt(i)) + 1);
             }
         }
         
         int j = 1, max = 0;
         char maxChar = ' ';
         StringBuffer result = new StringBuffer();
         
         
         for(Character c : charMap.keySet())
         {
             if(charMap.get(c) > max)
             {
                 max = charMap.get(c);
                 maxChar = c;
             }    
         }
         
         while(j <= max)
         {
             result.append(maxChar);
             j++;
         }
         
         return result.toString();
         
}

- Anonymous March 06, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This solution fails for the string "aabbccccddcc"

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

public class longestrunstring {
	public static void main(String args[]){
		String a = args[0];
		int max = 0;
		char longest = ' ';
		int count = 1;
		if(a.length() >0){
		for(int i = 1; i < a.length() - 1;i++){
			if(a.charAt(i) == a.charAt(i+1)){
				count++;
			}
			else {
				if(count+1 > max){
				max = count+1;
				longest = a.charAt(i);
				}
				count = 0;
			}
		}
		if(count+1 > max){
		max = count+1;
		longest = a.charAt(a.length()-1);		
		}
		if(max == 0){
			max = count+1;
			longest = a.charAt(0);
		}
		}
		for (int i = 0;i< max;i++)
			System.out.print(longest);
	}
}

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

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

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



int main(){

	char str[30] = "ssggggddhhhhh";
	
	char out = str[0];
	int count = 1;
	char m = out;
	int ma = count;
	for (int i = 1; i <= strlen(str); i++)
	{
		if(out == str[i])
			count++;
		else
		{
			count = 1;
		}
		//printf("%d",count);
		out = str[i];
	    //printf("%c",out);

		if(count > ma){

			ma = count;
			m = out;
		}
	}
	
	for (int i = 0; i < ma; i++)
	{
		printf("%c",m);
	}
	getchar();

}

- Bharat March 08, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void longestRep(string s) {
if(s.length() == 0)
return;

//string substr (size_t pos = 0, size_t len = npos) const;
string rst = s.substr(0, 1);
string tmp = rst;
for(int i = 1; i < s.size(); i++) {
if(s[i] == s[i - 1]) {
tmp += s[i];
}
else{
tmp.clear();
tmp += s[i];
}
rst = tmp.size() > rst.size() ? tmp : rst;

}
cout<<rst<<endl;

}

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

void print_runs(string s) {
  map<char,int> themap;
  string::iterator it = s.begin();
  char current = *it;
  int run = 1;
  ++it;
 
  for (;
       it != s.end();
       ++it) {
    if (*it == current)
      ++run;
    else {
      if (themap[current] < run)
	themap[current] = run;
      run = 0;
      current = *it;
    }
  }

  map<char,int>::iterator i;
  int print = 0;
  std::pair<char,int> ret;
  for (i = themap.begin();
       i != themap.end();
       ++i) {
    if ((*i).second > print) {
      print = (*i).second;
      ret.first = (*i).first;
      ret.second = (*i).second;
    }
  }

  cout << ret.first << " " << ret.second << " ";
  
  for (int j = 0; j < ret.second; ++j)
    cout << ret.first;
  cout << endl;

}

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

public static void calcLongest () {
    
    String text = "aabbbccaaadddde";
    
    char ch = 0;
    if ( text.length() > 0 ) {
      
      int longestIndexStart = 0;
      int longestLength = 1;
      
      int currIndexStart = 0;
      int currLength = 1;
      
      ch = text.charAt(0);
      for ( int i = 1 ; i < text.length(); ++i ) {
        if ( text.charAt(i) == ch ) {
          currLength++;
        } else {
          ch = text.charAt(i);
          if (currLength > longestLength) {
            longestIndexStart = currIndexStart;
            longestLength = currLength;
          }
          currIndexStart = i;
          currLength = 1;
          
        }
      }
      System.out.println(longestIndexStart + "\t" + longestLength);
      System.out.println( text.substring(longestIndexStart, longestIndexStart + longestLength ) );
    }
  }

- shekhar2010us March 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

There is a small error in the above code. It won't count the last character if that's the part of longest repeated sequence. Here is the correct code. Tested for all input data.

public static void calcLongest () {
    String [] texts = {"a" , "aab" , "aa" , "abbbbbcc" , "aabbccdd" , "aabbbccaaadddde"};
    for (String text : texts) {
      char ch = 0;
      if ( text.length() > 0 ) {
        int longestIndexStart = 0;
        int longestLength = 1;
        int currIndexStart = 0;
        int currLength = 1;
        
        ch = text.charAt(0);
        for ( int i = 1 ; i < text.length(); ++i ) {
          if ( text.charAt(i) == ch ) {
            currLength++;
          } else {
            ch = text.charAt(i);
            if (currLength > longestLength) {
              longestIndexStart = currIndexStart;
              longestLength = currLength;
            }
            currIndexStart = i;
            currLength = 1;
          }
        }
        if ( currLength > longestLength ) {
          longestIndexStart = currIndexStart;
          longestLength = currLength;
        }
        System.out.println( text + " --> " + text.substring(longestIndexStart, longestIndexStart + longestLength ) );
      }
    }
  }

- shekhar2010us March 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

char* longest_run(char* in)
{
	int highest_count = 1;
	int i_count=1;
	char prev = in[0];
	char final = prev;
	int cur=1;
	while(in[cur] != '\0')
	{
		if(in[cur] == prev)
		{
			i_count++;
			if(highest_count < i_count)
			{
				highest_count = i_count;
				final = prev;
			}
		}
		else
		{
			prev = in[cur];
			i_count=1;
		}
		cur++;
	}

	char *out = (char*)malloc(highest_count+1);
	out[highest_count] = '\0';
	memset(out, final, highest_count);

	return out;
}

- Sagar March 17, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

My solution in Python.
Time complexity: O(n)

def solution(s):
    # zm is a list of zeros to keep track of continuity 
    zm = [0 for _ in range(len(s))]
    for i, c in enumerate(s):
        if (i+1) < len(s):
            if c == s[i+1]:
                zm[i], zm[i+1] = 1, 1

    seq = set()
    seqs = []
    for i, flag in enumerate(zm):
        if flag == 1 and (i+1) < len(zm):
            if (i+1) - i == 1:
                seq.add(i)
                if zm[i + 1] == 1:
                    seq.add(i+1)
        else:
            if len(tuple(seq)) > 0:
                seqs.append(sorted(tuple(seq)))
            seq = set()

    lens = []
    for seq in seqs:
        lens.append(len(seq))
    max_len = max(lens)
    max_len_ind = lens.index(max_len)
    start = seqs[max_len_ind][0]
    end = seqs[max_len_ind][-1]
    print s[start:end+1]


if __name__ == '__main__':
    string = 'ehersdgfffghjhedeetyyyyy'
    solution(string)

- arunprasath9586 March 18, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

int main() {
	string mstr = "aaaaabbbccdd";
	int nLen = mstr.size();
	int nPStr = 0, nCStr = 0, nMax = 1, nCur = 1;

	int i = 1;
	while (i < nLen) {
		if (mstr[i] == mstr[i - 1]) nCur++;
		else {
			if (nCur > nMax) {
				nMax = nCur;
				nPStr = nCStr;
			} 
			nCStr = i;
			nCur = 1;
		}
		i++;
	}

	cout << nMax << ", str = " << mstr.substr(nPStr, nMax) << endl;
	cout << "Press enter to continue ..." << endl;
	cin.get();
	return 0;
}

- Passerby_A March 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

#include <iostream>
#include <string>

using namespace std;

string getLongestRun(const string &str){
  unsigned max_count =0;
  size_t max_char_start_idx = 0;
  for (size_t i=0; i<str.length(); ){
    int count=1;
    size_t j=i+1;
    for ( ;j<str.length() && str[j] == str[i]; ++j){
      ++count;
    }
    if (count > max_count) {
      max_count = count;
      max_char_start_idx = i;
    }
    i = j;
  }
  return str.substr(max_char_start_idx, max_count);
}

int main(){
  cout << getLongestRun("aaabbccbbbbdd") << endl;
  cout << getLongestRun("aabbccbbdd") << endl;
  cout << getLongestRun("aacd") << endl;
  cout << getLongestRun("acd") << endl;
  cout << getLongestRun("") << endl;
  cout << getLongestRun("aacddd") << endl;
  return 0;
}

- Anonymous March 25, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Good one!

- igorfact June 27, 2014 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Very nice! Straightforward and very efficient

- Morphage July 14, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

int run(char a[], int size, char *maxchar, int *maxcount)
{
    int count = 0;int i = 0;
    if (*maxcount <0)
        return -1;
    while (a[i] != '\0')
    {
        if (a[i] == a[i+1])
        {
            count++;
        }
        else if (*maxcount < count)
        {
            *maxchar = a[i];
            *maxcount = count;
            count = 0;
        }
        i++;
    }
    return 0;
}

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

Please comment the following code

int run(char a[], int size, char *maxchar, int *maxcount)
{
    int count = 0;int i = 0;
    if (*maxcount < 0)
        return -1;
    while (a[i] != '\0')
    {
        if (a[i] == a[i+1])
        {
            count++;
        }
        else if (*maxcount < count)
        {
            *maxchar = a[i];
            *maxcount = count;
            count = 0;
        }
        i++;
    }
    return 0;
}

- Anonymous March 30, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is correct, except that it returns the max run length - 1.
You should initiate your "count" variable to "1" since the first element is already a part of the run.

- Ehsan May 06, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public String getRun(String str){
char longestChar;
int longestLen=0;
Char[] cstr = str.toCharArray();
char nowChar = cstr[0];
int nowLen = 1;
longestChar = nowChar;
longestLen = nowLen;
for(int i=1; i<cstr.length; i++){

if(cstr[i]==nowChar){
nowLen++;
if(nowLen>longestLen){
longestChar = nowChar;
longestLen = nowLen;
}
}else{
nowChar = cstr[i];
nowLen= 1;
}
}
StringBuffer sb = new StringBuffer();
for(int i = 0 ; i<longestLen; i++){
sb.append(longestChar);
}
return sb.toString();
}

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

public static void printLongestRunString(String s){
		
		char currentlastChar =s.charAt(0);
		char longestchar = currentlastChar;
		int longestRun=1;
		int currentLongestRun =1;
		for(int i=1; i< s.length(); i++){
			char ch = s.charAt(i);
			if(ch==currentlastChar){
				currentLongestRun ++;
			}		
			else{
				if(currentLongestRun > longestRun){
					longestRun = currentLongestRun;
					longestchar = currentlastChar;
				}
				currentlastChar =ch;
				currentLongestRun =1;
			}
		}
		if(currentLongestRun > longestRun){
			longestRun = currentLongestRun;
			longestchar = currentlastChar;
		}
		for (int i = 0; i < longestRun; i++) {
			System.out.print(longestchar);
		}
	}

- GenAnswer April 11, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

In Ruby (tested with 2.1.1)

string_to_parse = ARGV[0]

def find_dupes_in_string str
  return "" if str.nil? || str.empty?
  puts str.scan(/((.)\2*)/).map(&:first).group_by(&:size).max.last
end

find_dupes_in_string string_to_parse

- dkerchner May 08, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

$ g++ longestRun.cpp
$ ./a.exe
Run String: aaakdnndjfjfklaaaaaaeeejjfeefffewwwewwwwww
Max Run Char: a Max Count: 5
Run String: aaaaaa
Max Run Char: a Max Count: 6
$ cat longestRun.cpp
#include <iostream>
#include <string>
#include <string.h>
#include <map>

using namespace std;

void printLongestRun(string inputString)
{
        int length=inputString.length();
        char *inputStringChars=new char[length+1];

        strcpy(inputStringChars,inputString.c_str());
        inputStringChars[length]='\0';

//      map<char,int> run;


        char currentChar;
        char previousChar=inputStringChars[0];
        int charCount=0;
        int maxCount=-1;
        char maxChar;
        for(int i=0;i<length;i++)
        {
          currentChar=inputStringChars[i];
          if(currentChar == previousChar) { charCount++; continue;}

//        map<char,int>::iterator it=run.find(previousChar);
//        if((it != run.end() && run[previousChar] < charCount) || it == run.end())
//              run[previousChar]=charCount;

          if(maxCount < charCount) {maxCount=charCount;maxChar=previousChar;}

          previousChar=currentChar;
          charCount=0;
        }
        if(maxCount < charCount) {maxCount=charCount;maxChar=previousChar;}

        cout<<"Run String: "<<inputString<<"\n";
        cout<<"Max Run Char: " << maxChar << " Max Count: "<<maxCount<<"\n";
}


int main()
{
 printLongestRun("aaakdnndjfjfklaaaaaaeeejjfeefffewwwewwwwww");
 printLongestRun("aaaaaa");

 return 0;
}
$

- Jaki May 10, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

std::string longRun(std::string s)
{
  if (s.empty()) return std::string(" ");
  if (s.length() == 1) return s;

  int maxRun = 1;
  int maxIndex = 0;
  int currRun = 1;
  for (int i = 1; i < s.length(); i++)  {
    if (s.at(i) != s.at(i-1)) {
      currRun = 1;
    } else {
      currRun++;
      if (currRun > maxRun) {
    maxRun = currRun;
    maxIndex = i+1-currRun;
      }
    }
  }
  
  return std::string(maxRun, s.at(maxIndex));
}

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

void printLongRun(char*s){
	if(s==null) return;
	if(*s == '\0') return;
	char bestChar = s[0];
	char currentChar = s[0]
	int maxRun = 1;
	int run = 1;
	s++;
	while(*s) {
		if(*s == bestChar) run++;
		else {
			if(run>maxRun) { 
				maxRun = run;
				bestChar = currentChar; 
			}
			currentChar = *s;
			run = 1;
		}
		++s;
	}

	while(maxRun-- > 0) {
		printf("%c", bestChar);
	}
}

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

This one is mine:

std::string GetLongestRun(const std::string& sInput)
{
    char chCurrent('\0'), chMax('\0');
    std::size_t nChNum(0), nChMaxNum(0);
    for(std::string::size_type pos = 0;pos<sInput.size();++pos)
    {
        if ( chCurrent!=sInput[pos] )
        {
            if ( nChNum>nChMaxNum )
            {
                chMax = chCurrent;
                nChMaxNum = nChNum;
            }
            nChNum = 0;
            chCurrent = sInput[pos];
        }
        ++nChNum;
    }

    return nChMaxNum>nChNum ? std::string(nChMaxNum, chMax) : std::string(nChNum, chCurrent);
}

- max.speed819 June 22, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// This one does not use random access to char array elements,
// so it should be more efficient

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

int main(int argc, char* argv[])
{
  if(argc!=2 || *argv[1]=='\0')
  {
    cout << "One argument: non-empty alfanumeric string" << endl;
    return 1;
  }
  
  int maxcnt = 1; //maximum run count
  char* str = argv[1];
  int rcnt = 1;  //current run count
  char c = *(str++); //current character
  char maxc = c;  //maximum run character
  
  while (*str != '\0')
  {
    if(*str==c)
      rcnt++;
    else
    {
      if(rcnt > maxcnt)
      {
        maxcnt=rcnt;
        maxc=c;
      }
      rcnt=1;
    }
    c=*(str++);
  }
  
  if(rcnt > maxcnt)
  {
    maxcnt=rcnt;
    maxc=c;
  }
  
  cout << string(maxcnt, maxc) << endl;
}

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

Hi everyone,
I use Python for this question:
i and j are used as a pointer to the index number of characters in the given string.

###############################

def LCS(s):
    i,j = 0,1  
    ret = ''

    if len(s)==0 or len(s)==1:
        return s
    else:

        ret = s[i:j]
        while(j < len(s)):
            if s[i] != s[j] or s[j]== s[:-1]:
                # move both index to the next one 
		if j-i == 1:
                    i += 1
                    j += 1
                else:
                    if len(ret) < (j-i): # if return string doesn't have maximum length
                        ret = s[i:j]
                    i += (j-i)
                    j += 1
            else: 
	# find duplicated character, beginning character (is at i) remains the same while 
	# j moves to the next index to compare with character at i
                j += 1
                if len(ret) < (j-i):
                    ret = s[i:j]
        return ret

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

void printLongestRun(const string &str){
    if (str.length() <=1) {
        cout <<str<<"\n";
        return;
    }
    unsigned cur =0, next=0, max =0, max_start =0;
    while(str[cur]){
        while (next < str.length() && str[cur] == str[next]) ++next;
        unsigned end = (next != str.length()) ? next-1 : str.length()-1;
        if (end - cur + 1 > max){
            max = end - cur + 1;
            max_start = cur;
        }
        cur = next;
    }
    cout << str << "\t=>"<<str.substr(max_start, max) << "\n";
}

- im.code.warrior July 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void printLongestRun(const string &str){
    if (str.length() <=1) {
        cout <<str<<"\n";
        return;
    }
    unsigned cur =0, next=0, max =0, max_start =0;
    while(str[cur]){
        while (next < str.length() && str[cur] == str[next]) ++next;
        unsigned end = (next != str.length()) ? next-1 : str.length()-1;
        if (end - cur + 1 > max){
            max = end - cur + 1;
            max_start = cur;
        }
        cur = next;
    }
    cout << str << "\t=>"<<str.substr(max_start, max) << "\n";
}

- im.code.warrior July 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void printLongestRun(const string &str){
    if (str.length() <=1) {
        cout <<str<<"\n";
        return;
    }
    unsigned cur =0, next=0, max =0, max_start =0;
    while(str[cur]){
        while (next < str.length() && str[cur] == str[next]) ++next;
        unsigned end = (next != str.length()) ? next-1 : str.length()-1;
        if (end - cur + 1 > max){
            max = end - cur + 1;
            max_start = cur;
        }
        cur = next;
    }
    cout << str << "\t=>"<<str.substr(max_start, max) << "\n";
}

- im.code.warrior July 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String getLongestRun(String str){
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		Character cur = str.charAt(0);
		int count = 0;
		for(int i=0; i<str.length(); i++){
			if(str.charAt(i) == cur){
				count++;
				if(map.get(cur) == null){
					map.put(cur, count);
				}else{
					if(map.get(cur) < count){
						map.put(cur, count);
					}
				}
			}else{				
				cur = str.charAt(i);
				count = 0;
			}
		}
		Character maxChar = null;
		int maxCount = 0;
		for(Character c : map.keySet()){
			if(map.get(c) > maxCount){
				maxCount = map.get(c);
				maxChar = c;
			}
		}
		for(int j=0; j<maxCount; j++){
			System.out.print(maxChar);
		}
		
		
		return null;
	}

- WBin.Beyond July 21, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

static void Main(string[] args)
        {
            string s = Console.ReadLine();

            char[] a = s.ToCharArray();
            Dictionary<string, int> collection = new Dictionary<string, int>();

            foreach (var i in a)
            {
                if (!collection.ContainsKey(i.ToString()))
                {
                    collection.Add(i.ToString(), 1);
                }
                else
                {
                    collection[i.ToString()] = collection[i.ToString()] + 1;
                }
            }

            foreach (var item in collection.OrderByDescending(x => x.Value))
            {
                int x = item.Value;
                while (x >= 1)
                {
                    Console.Write(item.Key);
                    x -= 1;
                }
                Console.ReadKey();
                return;
            }
        }

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;



class A{

public A() {
System.out.println("This is class A construtor");
}

public static void main(String args[])
{
System.out.println("Enter the String ");

try{
BufferedReader line = new BufferedReader(new InputStreamReader(System.in) );
String input = line.readLine();
input+=" ";


int maxvalue=0;
String result="",finalString="";

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



if(input.charAt(i)==input.charAt(i+1)){
result+=input.charAt(i);

}
else{
if(result.length()>maxvalue){
maxvalue=result.length();
finalString=result+input.charAt(i);



}
result="";
}


}
System.out.println("Result ="+finalString);
System.out.println("Result length ="+finalString.length());
}
catch(Exception e){
System.out.println("Exception Occured ="+e.getMessage());
e.printStackTrace();
}

}

}

- Puneet Jain August 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

char* getLongestRun(char []);

int main()
{
char *str=getLongestRun("abbbbbccdd");
printf("\n%s\n",str);
str=getLongestRun("aaabbccbbbbdd");
printf("\n%s\n",str);
str=getLongestRun("aabbccbbdd");
printf("\n%s\n",str);
str=getLongestRun("aacd");
printf("\n%s\n",str);
str=getLongestRun("aacddd");
printf("\n%s\n",str);
return 0;
}

char* getLongestRun(char s[])
{
if(!s)
{
printf("String is NULL,System exiting\n");
exit(0);
}
int length=strlen(s);
if(length==0)
{
printf("string is empty,System exiting\n");
exit(0);
}
char *str=(char *)malloc(sizeof(length+1));
int i=0,count=0,max=1,j=0;
int start_index_count=0,end_index_count=0;
for(i=0;i<length;i++)
{
count=1;
        for(j=i;j<length;j++)
        {
                if(s[j]==s[j+1])
                {
                count++;
                }
                else
                {
                break;
                }
        }
        if(count>max)
        {
        start_index_count=i;
        end_index_count=j;
        max=count;
        }
}
printf("Longest run count is %d",max);
for(i=start_index_count,j=0;i<=end_index_count;i++,j++)
        *(str+j)=s[i];
return str;
}

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

#include <stdio.h>
int main()
{
int currentNumberOfOcc=1, previousNumberOfOcc =1, i=0;
char inputString[200], currentChar=-1, previousChar=-1;
printf ("Enter the string = ");
fgets(inputString, 200, stdin);

for(i=0; i < strlen(inputString); i++)
{
currentChar = inputString[i];
if (currentChar == inputString[i+1])
{
currentNumberOfOcc++;
}
else
{
if (currentNumberOfOcc >= previousNumberOfOcc && inputString[i+1]
!=NULL)
{
previousNumberOfOcc = currentNumberOfOcc;
previousChar = currentChar;
}
currentNumberOfOcc =1;

}
}
for (i =0;i< previousNumberOfOcc; i++)
{
printf ("%c",previousChar);
}
printf ("\n");

}

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

I solved problem in java,

public static void main(String[] args){
		
		Scanner in= new Scanner(System.in);
		
		String s= in.next();
		
		ArrayList<Character> currentLogest=new ArrayList<>();
		ArrayList<Character> current=new ArrayList<>();
		int lengtOfcurrentLongest=0, currentLength=0;
		char prev = s.toCharArray()[0];
		
		
		for(char c : s.toCharArray()){
			
			if(prev==c)
			{
				current.add(c);
				prev=c;
				if(current.size()>currentLogest.size())
				{
					currentLogest=new ArrayList<>();
					currentLogest=current;
					
				}
			}
			else
			{
				current=new ArrayList<>();
                                                                                                                                                                  				current.add(c);
				prev=c;
				System.out.println(current);
				if(current.size()>currentLogest.size()){
					
					currentLogest=new ArrayList<>();
					currentLogest=current;
				}
			}
			
			
		}
		
		System.out.println("Size: " + currentLogest.size() + " longest run: " + currentLogest );
		
	}

- ATuring September 20, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I used C++11:

#include <iostream>
using namespace std;

int main() {
	string s = "kaasssaaddddee";
	int start = 0, end = 0, temp_start = 0, temp_end = 0;
	int i = 0;
	for(i = 1;i < s.length();i++){
		if(s[i] == s[temp_start]) temp_end++;
		else{
			if(temp_end - temp_start > end - start){
				start = temp_start;
				end = temp_end;
			}
			temp_start = i;
			temp_end = i;
		}
	}
	cout << s.substr(start, end - start + 1);
	return 0;
}

- kshaf October 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The previous code fails if the part with maximum number of characters is at the and of the string. Here's how it can be fixed:

#include <iostream>
using namespace std;

int main() {
	string s = "kaasssaaddddeejjjjjj";
	int start = 0, end = 0, temp_start = 0, temp_end = 0;
	int i = 0;
	for(i = 1;i < s.length();i++){
		if(s[i] == s[temp_start]){
			temp_end++;
			if(temp_end - temp_start > end - start){
				start = temp_start;
				end = temp_end;
			}
		} 
		else{
			if(temp_end - temp_start > end - start){
				start = temp_start;
				end = temp_end;
			}
			temp_start = i;
			temp_end = i;
		}
	}
	cout << s.substr(start, end - start + 1);
	return 0;
}

- kshafiee October 01, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

void LongestRun(const string &s)
{
	char run_char = ' ';
	int max_count = 0;
	int curr_count = 0;

	char ch = ' ';
	for (int i = 0; i < s.length(); i++)
	{
		if (s[i] != ch)
			curr_count = 0;

		curr_count++;
		ch = s[i];

		if (curr_count > max_count)
		{
			run_char = ch;
			max_count = curr_count;
		}
	}

	for (int i = 0; i < max_count; i++)
		cout << run_char;
	cout << endl;
}

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

void LongestRun(const string &s)
{
	char run_char = ' ';
	int max_count = 0;
	int curr_count = 0;

	char ch = ' ';
	for (int i = 0; i < s.length(); i++)
	{
		if (s[i] != ch)
			curr_count = 0;

		curr_count++;
		ch = s[i];

		if (curr_count > max_count)
		{
			run_char = ch;
			max_count = curr_count;
		}
	}

	for (int i = 0; i < max_count; i++)
		cout << run_char;
	cout << endl;
}

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

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

int main()
{

char a[]="abbbbbbbbcccccyyyyyyyyy";
a[strlen(a)]='\0';

int i,j=0;
int first=0;
int last=0;
int count=1;
int max=0;
for(i=0;i<strlen(a);i++)
{
	if(a[i]!=a[i+1])
	{
		if(count>max)
        	{
        		first=j;
			last=i;
        		max=count;
        	}
		j=i+1;
		count=1;
	}
	else
	count++;
}
printf("\n");
for(i=first;i<=last;i++)
printf("%c", a[i]);
}

- Payel Hazra October 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

std::string getLongestRun(const std::string& str)
{
char longestRunChar = str[0];
unsigned int length = 1;

char currLongestRunChar = str[0];
unsigned int currLength = 1;

char prevChar = str[0];

for (int index = 1; index < str.length(); ++index)
{
if (str[index] == prevChar)
{
++currLength;
}
else
{
if (currLength > length)
{
length = currLength;
longestRunChar = currLongestRunChar;
}
currLongestRunChar = str[index];
currLength = 1;
}
prevChar = str[index];
}

return string(length, longestRunChar);
}

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

It seems alot of this code is unnecessarily complex. This is what I did:

std::string longest_run(std::string s){
	std::string cur = "";
	cur += s[0];
	std::string max = cur;
	for(int i = 1; i < s.size(); i++){
		if(s[i] == cur.back()) cur += s[i];
		else cur = s[i];
		if(cur.size() > max.size()) max = cur;
	}
	return max;
}

- Quinn December 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static String getLongestRun(String s){
        int i = 0, j = 1;
        String tempString = s.substring(0, 1);
        for(i = 0; i < s.length() && j < s.length();){
            while(j < s.length() && s.charAt(i) == s.charAt(j))
            {                
                j++;
            }
            //System.out.println("i = " + i + " j = " + j + " temp = " + s.substring(i, j));
            
            if(tempString.length() < (j-i))
            {
                //System.out.println("Changed");
                tempString = s.substring(i, j);
                
            }
            //System.out.println(tempString);
            i = j;
            j++;
            
            
        }
        
        return tempString;
    }

- Chetan Pawar January 12, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>

char *longest_run(char *str) {
	char *index = str, max_char = *str, curr_char;
	int curr_run, max_run = 1;
	
	while (*index != '\0') {
		curr_char = *index;
		curr_run = 0;
		while (*index == curr_char) {
			index++;
			curr_run++;
		}
		
		if (curr_run > max_run) {
			max_run = curr_run;
			max_char = curr_char;
		}
	}
	
	index = str;
	while (max_run > 0) {
		*index++ = max_char;
		max_run--;
	}
	
	*index = '\0';
	return str;
}

int main() {
	char str[] = "aabbccccddcc";
	printf(longest_run(str));
	printf("\n");
	return 0;

}

- Austin Nwachukwu January 20, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Ideone
{
	public static void main (String[] args) throws java.lang.Exception
	{
		printLongest("abbbbcc");
	}
	
	public static void printLongest(String s)
	{
		char ch = s.charAt(0), maxCh=s.charAt(0);
		int max = 0;
		int counter = 1;
		for(int i=1; i < s.length(); i++)
		{
			char c = s.charAt(i);
			if(c == ch)
				counter++;
			else 
			{
				if(counter>max)
				{
					max = counter;
					maxCh = ch;
				}
				
				counter = 1;
				ch = c;
			}	
			
			if(i==s.length()-1)
			{
				if(counter>max)
				{
					max = counter;
					maxCh = ch;
				}
			}
		}
		
		for(int i = 0; i < max; i++)
		{
			System.out.print(maxCh);
		}
	}
}

- undefined February 26, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 3 vote

public String longestRun(String str) {
		int maxLen = 1;
		int maxStart = 0;
		int curStart = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) != str.charAt(curStart)) {
				if (i - curStart > maxLen) {
					maxLen = i - curStart;
					maxStart = curStart;
				}
				curStart = i;
			}
		}
		return str.substring(maxStart, maxStart + maxLen);
	}

- seedmanee March 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

elegant solution

- zhwojw April 15, 2014 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

not correct for the input "aaaaaa"

- yx April 21, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

public String longestRun(String str) {
int maxLen = 1;
int maxStart = 0;
int curStart = 0;
for (int i = 0; i <= str.length(); i++)
{
if (i==str.length() || str.charAt(i) != str.charAt(curStart))
{

if (i - curStart > maxLen) {
maxLen = i - curStart;
maxStart = curStart;
}
curStart = i;
}
//else if(maxStart==0 && curStart==0)
//maxLen++;


}
return str.substring(maxStart, maxStart+maxLen);
}

- harish May 31, 2014 | Flag
Comment hidden because of low score. Click to expand.
-2
of 2 votes

In addition to the bug pointed out by yx, the task was to write a "program", not just a function, and to "print" the longest run.

- igorfact June 27, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 votes

@igorfact: Seriously, that is your concern? You can't write a program yourself, given that function?

- Anonymous June 27, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The problem as pointed out that if input string end with the longest sequence it would find it.
E.g.: str = "aabbbbb" it would print "aa".

- Anonymous August 15, 2014 | 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