Adobe Interview Question


Country: India




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

I don't think it's possible if we don't know the indices of the replaced char. Perhaps we could create a kind of proxy around the string and perform the update lazily when the string is requested. Otherwise, it can't be better than O(n), because the worst case requires to modify all the characters.

- Danstahr April 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Generally while asking these questions they will say assume Input as below.

S - Source String
C - Char to find.
K - No of times C repeated in string.
N - Length of chars in S.

K < N.

So no need to worry about all chars as same in S.

We may need give solution with K length.

- Srigopal Chitrapu June 10, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Agreed , but if you preprocess the string and store <character,indices> as a HashMap and assuming the string is in an array O(1) should be possible . As this would involve a hashmap lookup & updation to String

- Sorrowfull Blinger September 13, 2014 | Flag
Comment hidden because of low score. Click to expand.
3
of 3 vote

How can we do it in less than O(n). What if all the n charecters are the same charecter (which is to be replaced).

- arsragavan April 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 2 vote

As pointed out by @Kid of Kop, I doubt a O(n) solution...

Below is a C version of O(n) solution:

void ReplaceChar ( char *str, char Find, char Replace ) {
   while ( *str ) {
        if ( *str == Find )
            *str = Replace ;
        str++ ;
    } 
}

- R@M3$H.N April 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

as there is no constraint regarding what character has to be substituted,we just add one to each char,

ex:if i/p is ABCa
o/p wil be BCDB.

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

I think we can use bitwise operators to mask all non-replaceable characters and then OR with to-be replaced character and then merge back to main string ?

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

u should have asked interviewer if the string is sorted.
If the given string is sorted then:
Just find the character using binary search and from there start replacing

And how about this :

for(int i=0;i<l/2;i++)
{
   if(a[i]=='character to replace')
     replace it
   elseif(a[l-i]=='character to replace')
    replace it
}

- Registered June 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

for(int i=0;i<l/2;i++)
{
   if(a[i]=='character to replace')
     replace it
   if(a[l-i]=='character to replace')
    replace it
}

- Registered June 23, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

u should have asked interviewer if the string is sorted.
If the given string is sorted then:
Just find the character using binary search and from there start replacing

And how about this :

for(int i=0;i<l/2;i++)
{
   if(a[i]=='character to replace')
     replace it
   elseif(a[l-i]=='character to replace')
    replace it
}

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

get 2 pointers one to the start and one to end.

while( start != end )
{
if(*start == 'c' || *end == 'c' )
{
code to replace(char);
}
start++;
end--
}

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

String str = "abcaera";
		char a = 'a';
		char r = 'z';
		char[] chars = str.toCharArray();
		int l = chars.length-1;
		int c = 0;
		for(int i=0; i<=l/2; i++) {
			if(chars[i] == a) {
				chars[i] = r;
			} 
			
			if(chars[l-i] == a) {
				chars[l-i] = r;
			} 
			c++;
		}
		System.out.println("Original String = " + str);
		System.out.println("Replaced String = " + new String(chars));
		System.out.println("Number of interations = " + c);

- Shankar September 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

I dont think its possible in less than O(n) as we have to traverse all the characters of string at least once

- An Enthusiast April 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

If the string was originally sorted, maybe binary search, find the first occurrence of the char and substitute.

Still, the worst case would be O(n) if all the characters in the string are the same as has been pointed out by others.

- tejaswi.yvs April 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Also it would need a binary search algorithm with extra storage for values

1) Traverse the string and build binary search data structure with indexes stored as values(in a linked list) - This is only once
2) Write a replace function that would find the search character using binary search and get the index list
3) Traverse the index list and replace the characters at the index location by direct index reference.

- It would be possible if n is not equal to count(findAll(searchString)) April 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Assuming you are allowed to keep track of a list of each character's positions while the string is built, then the best and average case of 'replaceChar()' would be < O(n). What do you guys think?

import java.util.*;

public class HelloWorld {

    static Map<Character, List<Integer>> positions = new HashMap<Character, List<Integer>>();

    public static void main(String []args) {
        String s = buildString('h','e','l','l','o',' ','w','o','r','l','d');
        System.out.println("s: " + s);
        System.out.println(positions);
        s = replaceChar(s, 'l', 'X');
        System.out.println("s: " + s);
    }
    
    static String buildString(char... chars) {
        String s = null;
        for (char c : chars) {
            s = append(s, c);
        }
        return s;
    }
    
    static String append(String s, char c) {
        if (s == null) s = "";
        String newS = s + c;
        List<Integer> charPositions = positions.get(c);
        if (charPositions == null) {
            charPositions = new ArrayList<Integer>();
            positions.put(c, charPositions);
        }
        charPositions.add(newS.length()-1);
        return newS;
    }
    
    static String replaceChar(String s, char c, char newC) {
        List<Integer> charPositions = positions.get(c);
        if (charPositions == null) return s;
        char[] charArr = s.toCharArray();
        for (int pos : charPositions) {
            charArr[pos] = newC;
        }
        return new String(charArr);
    }
}

Output is:

s: hello world
{w=[6], d=[10], =[5], e=[1], r=[8], o=[4, 7], l=[2, 3, 9], h=[0]}
s: heXXo worXd

- caleb.cittadino April 23, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

We cannot assume that way as input might already build as it may come from any sources and we cannot ask them to maintain extra n length space to retain their indices. Focus on 'string algorithms'.

- Srigopal Chitrapu June 10, 2014 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

How abt using Merge sort/binary search concept by diving array into half.....ord( log n).
#include <stdlib.h>
#include <stdio.h>

void replacCharinString( char *cpystr, int i, int j, char *x, char *y){
     
     if( i==j){ if(cpystr[i]== *x) cpystr[i]= *y; return;}
     
     replacCharinString( cpystr,i,(i+j)/2, x,y);
     replacCharinString( cpystr,(i+j)/2+1,j, x,y);
     }

main(){
       int i,count;
       char a,b;
       char str[100];
       printf("enter a string     ");
       scanf("%s",str);
       a=getchar(); // this is used to get rid of "\n" as a character;
       printf("enter a character that u need to replace in given string     ");
       a=getchar();
       b=getchar(); // this is used to get rid of "\n" as a character;
       printf("enter a character that  by which u wnat to replace in given string     ");
       b=getchar();
       i=0;count=0;
       while ( str[i] != '\0'){ i++; count++;}
       replacCharinString( str,0,count-1,&a,&b);
       printf("Replaced string is  %s\n",str);
       
       scanf("%d",&i);
       
       }

- sumit June 04, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Should use string algorithms. Divide and Conquer is bad idea as it fails if we need to search for multiple chars.

- Srigopal Chitrapu June 10, 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