Move Zeroes - codepath/compsci_guides GitHub Wiki

TIP102 Unit 1 Session 2 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: List Manipulation, Two Pointers

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • The function move_zeroes() should take a list of integers and move all zeroes to the end while maintaining the relative order of non-zero elements.
HAPPY CASE
Input: [1, 0, 2, 0, 3, 0]
Expected Output: [1, 2, 3, 0, 0, 0]

Input: [0, 1, 0, 3, 12]
Expected Output: [1, 3, 12, 0, 0]

EDGE CASE
Input: [0, 0, 0]
Expected Output: [0, 0, 0]

Input: [1, 2, 3]
Expected Output: [1, 2, 3]

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use a loop to iterate through the list and separate non-zero elements from zero elements. Append non-zero elements first followed by all zero elements.

1. Define the function `move_zeroes(nums)`.
2. Initialize an empty list `result` to store the final result.
3. Initialize a counter `zero_count` to keep track of the number of zeroes in the list.
4. Iterate through the list `nums`:
   - If the current element is not zero, append it to `result`.
   - If the current element is zero, increment `zero_count`.
5. After the iteration, append `zero_count` number of zeroes to the end of `result`.
6. Return the `result` list

⚠️ Common Mistakes

  • Not counting zeroes correctly.
  • Forgetting to append zeroes at the end.

I-mplement

Implement the code to solve the algorithm.

def move_zeroes(nums):
    result = []
    zero_count = 0
    
    # Iterate through the list and append non-zero elements to result
    for num in nums:
        if num != 0:
            result.append(num)
        else:
            zero_count += 1
    
    # Append the zeroes to the end of the result list
    for _ in range(zero_count):
        result.append(0)
    
    return result