Apple Interview Question for Software Engineer / Developers


Country: United States
Interview Type: In-Person




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

void remove_spaces(char* string) {
  if (string == NULL) return;
  char* copy_to = string;
  char* copy_from = string;
  while (*copy_from != '\0') {
    if (*copy_from == ' ') { copy_from++; continue; }
    *copy_to = *copy_from;
    copy_from++;
    copy_to++;
  } 
  *copy_to = '\0';
}

- Martin October 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This might fail in case, we have two or more spaces lying together, for e.g., in the case of the following string- {'a', ' ', ' ', 'b'}. Instead of

if (*copy_from == ' ')

we should loop around to check if there are even more spaces.

- pikoooz January 24, 2013 | Flag
Comment hidden because of low score. Click to expand.
2
of 2 votes

It won't fail if there are multiple spaces. It continues to increment the copy_from pointer for every space it sees.

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

You're considering ' ' as space. There are other kinds of space, such as `\t`.

So instead of this:

if (*copy_from == ' ')

you should do this:

if ( isspace(*copy_from) )

which checks for other spaces as well.

- Nawaz April 14, 2013 | Flag
Comment hidden because of low score. Click to expand.
4
of 4 vote

void removeSpaces(char* source){
    if(source == NULL)
        return;
    char* i = source;
    char* j = source;
    while(*j){
        *i = *j++;
        if(*i != ' '){
            i++;
        }
    }
    *i = '\0';
}

- m3th0d.itbhu April 05, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 3 vote

// Assumes in-place removal of spaces
// Time O(n) - Space O(1)
void removeSpaces(char* s) {
  if (!s) {
    return;
  }
  char* nonwhite = s - 1;
  char* itr = s;
  while (*itr) {
    if (*itr != ' ') {
      *(++nonwhite) = *itr;
    }
    ++itr;
  }
  *(++nonwhite) = '\0';
}

- windcliff October 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

It is potentially dangerour to set char* nonwhite = s - 1;
It then points to a position that is practically an illegal address!
I know that because of the prefix increment this addressing won't happen but why are you afread of using postfix increments?

- Selmeczy, Péter October 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

It is not, because the variable "nonwhite" is always pre-incremented before being used. In the local bind of the method, you can set whatever value for the variables. Only accessing the memory at the position (s-1) can be dangerous, but it is never done, since nonwhite is always pre-incremented, and so its first value when used is s.

- Riccardo November 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

O(n):

remove_spaces(char *str) {
	char *temp;
	char *cur;

	cur = str;

	while (*cur != '\0' && *cur != ' ' ) {
		cur++;
	}

	temp = cur;

	while (temp != '\0') {
		if (temp != ' ')
			*cur = *temp;
			cur++;
		}
		temp++;
	}
	*cur = '\0';
}

- guest October 05, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

char *trimspace(char *str)
{
char *str1,*str2;
str1=str;
str2=str;
while(*str1)
{
if (*str1!=' ')
{
*str2=*str1;
str1++;
str2++;
}
str1++;
}
*str2='\0'
return str2;
}

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

#include<stdio.h>
#include<conio.h>
int main()
{
char ch[]="ram is a good boy";
int i;
for(i=0;i<20;i++)
{
if(ch[i]==' ')
continue;
else
printf("%c",ch[i]);
}
getch();
return 0;
}

- rahulkumar642 October 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

This one does not remove the spaces in the source string... it just prints the string without printing the spaces... not the complete solution...

- JustCoding October 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static void RemoveSpaces()
{
string temp = "nayni sh sdfg j k k";
char[] myArr = temp.ToCharArray();
SpaceCheck(ref myArr, 0, 0);
foreach (char item in myArr)
{
Console.Write(item);
}
}


private static void SpaceCheck(ref char[] myArr, int i, int j)
{
if (i < myArr.Length)
{
if (Char.IsWhiteSpace(myArr[i]))
{
if (!Char.IsWhiteSpace(myArr[j]))
{
j++;
SpaceCheck(ref myArr, i, j);
}
else
{
i++;
SpaceCheck(ref myArr, i, j);
}
}
else if (!Char.IsWhiteSpace(myArr[i]))
{
if (Char.IsWhiteSpace(myArr[j]))
{
char temp;
temp = myArr[i];
myArr[i] = myArr[j];
myArr[j] = temp;
i++; j++;
SpaceCheck(ref myArr, i, j);
}
else
{
j++; i++;
SpaceCheck(ref myArr, i, j);
}
}
}
}

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

private static void RemoveSpaces()
{
string temp = "nayni sh sdfg j k k";
char[] myArr = temp.ToCharArray();
SpaceCheck(ref myArr, 0, 0);
foreach (char item in myArr)
{
Console.Write(item);
}
}

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

private static void RemoveSpaces()
{
string temp = "fsdkjgfsd sds aads dd f ";
char[] myArr = temp.ToCharArray();
StringBuilder sb = new StringBuilder();
foreach (char item in myArr)
{
if(!Char.IsWhiteSpace(item))
{
sb.Append(item);
}
}
Console.WriteLine(sb);
}

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

int _tmain(int argc, _TCHAR* argv[])
{
int i=0,j=0;
char str[]="spa ci ous string occ ur ed";
while(i<strlen(str))
{
if(str[i]==' ')
{
i++;


}
else
{
str[j]=str[i];
++i;
++j;

}

}
str[j]='\0';
std::cout<<str;
getch();
return 0;
}

- aaman.singh85 October 11, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

private static String removeSpaces(String str)
{
String res = new String();

for(int i=0; i<str.length(); i++)
{
if(!(str.charAt(i)==' '&& (i<str.length()-1)))
{
res += str.charAt(i);
}

}
return res;
}

- lyubomir December 02, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void reverse_String(char *str) {
        int len = strlen(str) - 1;
        int i = 0, j = 0;

       for(i = 0; i < n; i++) {
            if(str[i] == ' ' | str[i] == '\t\) {}
            else {
                          str[j] = str[i];
                          j++;
           }
        }

        str[j] = '\0';
}

- Hitesh December 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

what is n here, n=len

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

void remove_space_from_a_string(char *oldstring, char *newstring)
{
while(*oldstring !='\0')
{ if(*oldstring != ' ')
{ *newstring = *oldstring;
newstring++; oldstring++;
}
else
oldstring++;
}
*newstring = '\0 ';
}

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

I would like to change the code a little bit to make it better:

void remove_space_from_a_string(char *oldstring)
{
char *newstring;
newstring = oldstring;
while(*oldstring !='\0')
{ if(*oldstring != ' ')
{ *newstring = *oldstring;
newstring++; oldstring++;
}
else
oldstring++;
}
*newstring = '\0 ';
}

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

The in-place solution has complexity of O(N^2) because you have to move the characters following a space after it's removed. (N characters moved N times).

By copying the string we don't have to move any characters so the solution is O(N). Only one pass is necessary if we can return the copied string, otherwise a second pass is necessary to copy it back to the original. Either way it's still O(N).

- Barry Fruitman March 17, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

No, it is O(n). The movement is done while iterating through the string. If a string has N chars, then the loop will be executed N times, not N*N times.

- Tristan Muntsinger March 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Good point. I was confusing this "remove" problem with an "insert" problem which would require moving all the chars every time.

- Barry Fruitman March 17, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{
void remSpace(char*str)
{
int index = 0;
for(int i =0;str[i] ;i++)
{
if(str[i] != ' ')
str[index++]= str[i];
}
str[index] = '\0';
}
}}

- SDGuy April 04, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{

void remSpace(char*str)
{
int index = 0;
for(int i =0;str[i] ;i++)
{
if(str[i] != ' ')
str[index++]= str[i];
}
str[index] = '\0';
}

}}

- SDguy April 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

{{
void remSpace(char*str)
{
int index = 0;
for(int i =0;str[i] ;i++)
{
if(str[i] != ' ')
str[index++]= str[i];
}
str[index] = '\0';
}
}}

- SDguy April 09, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void remove_spaces(char* str)
{
	int count = 0;
	for(int i = 0; str[i] != '\0'; ++i)
	{
		if(str[i] == ' '){ ++count; }
		else { str[i - count] = str[i]; }
	}
}

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

char* nospace(char *s){
	char *buffer = malloc(strlen(s));
	int i=0;
	while (*s != '\0'){
		if(*s != ' '){
			buffer[i] = *s;
			i++;
		}
		*s++;		
	}
	return buffer;
}

Time: O(n) Space: O(1)

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

Java solution

String s="yes I can delete spaces";
		StringBuilder sb=new StringBuilder(s);
		int numberOfDeletes=0;
		for(int i=0; i<s.length()-1; i++)
		{
			if(s.charAt(i)==' ')
			{
				sb.deleteCharAt(i-numberOfDeletes);
				numberOfDeletes++;
			}
		}
		
		s=sb.toString();
		System.out.println(s);

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

A python solution:

def removeSpaces(inputString):
	length=len(inputString)
	numberOfdeletions=0
	for i in range(0,length):
		if inputString[i-numberOfdeletions]==' ':
			print "here"
			nwLength=length-numberOfdeletions
			inputString=inputString[:i-numberOfdeletions]+inputString[i+1-numberOfdeletions:]
			numberOfdeletions+=1
			print numberOfdeletions
	print inputString

- ATuring August 27, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

char[] foo(char str[])
{
  char* c = str;
  while(*c!='\0'){
    if(*c == ' '){
      *c++='\0';
      strcat(str, c);
    }
    c++;
  }
  return str;
}

- code_monkey October 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Time: O(n). Space: O(1)

- code_monkey October 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This one does not work... throwing "System.AccessViolationException" error.

- JustCoding October 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Calling strcat is killing the O(n)!
First it is reading to the end of the first string and then it it copying the 2nd string!

- Selmeczy, Péter October 04, 2012 | 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