DEV Community

Discussion on: 6-10PM challenge problem #001

Collapse
 
bradtaniguchi profile image
Brad • Edited

This is my "code-golf-esque" solution.

const arr = [12, 3, 0, 2, 8, 11, 0, 0, 6, 4, 0, 5, 7, 0, 8, 9, 0];

const combine = ({ nums, zeros }) => [...nums, ...zeros];
const moveZeroes = arr =>
  combine(
    arr.reduce(
      (acc, num) =>
        (num === 0 ? acc.zeros.push(num) : acc.nums.push(num)) && acc,
      {
        nums: [],
        zeros: []
      }
    )
  );

console.log(moveZeroes(arr));

I wasn't to sure about what the "naive brute force" is. My current solution should always run at 2n where n is the number of integers in the array, this assumes the combine method just iterates the two arrays together.

I'm 100% sure there is a 1n approach, where you iterate over the array only 1 time, but I personally hate working on arrays I'm iterating over.

edit I didn't see this was tagged as a Java problem, and the above is JavaScript, so it is what it is haha.

Collapse
 
akbhairwal profile image
akbhairwal

oh Sorry... I should make it language independent..
I think it can be done in single array iteration and having two pointer for swapping