Skip to content

Instantly share code, notes, and snippets.

@dubeme
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dubeme/6ac79fd13000e0568200 to your computer and use it in GitHub Desktop.
Save dubeme/6ac79fd13000e0568200 to your computer and use it in GitHub Desktop.
Amazon phone interview question
/*
Start from the end of the array
If I come across a non zero,
move it to before the last known
location of a non zero number
*/
void rearrangeArray(int[] nums)
{
int lastNonZero = nums.length - 1;
boolean foundZero = false;
for(int i = nums.length - 1; i>= 0; i--)
{
foundZero = foundZero || nums[i] == 0;
if(nums[i] != 0)
{
if ( foundZero )
{
nums[lastNonZero] = nums[i];
nums[i] = 0;
}
lastNonZero -= 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment