logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

283. Move Zeroes

1 min read
On this pageIntitution
IntitutionComplexityCode

# Intitution

Instead of moving non-zeros forward and filling zeros later use two pointers (i and j) place non-zero elements at the correct spot (j) also immediately sets the current i to 0 if a movement has occurred


So, it shifts non-zeros forward and backfills zeros in one go

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(n)\text{O}(n)O(n)

# Code

public void moveZeroes(int[] nums) {
    for (int i = 0, j = 0; i < nums.length; ) {
        if (nums[i] != 0) {
            nums[j] = nums[i];           // Place the non-zero at index j
            if (j != i) nums[i] = 0;     // If i != j, we've moved something — set old spot to 0
            ++j;                         // Move j to the next available slot
        }
        ++i; // Always move i to check next element
    }
}
←Previous242. Valid AnagramNext→345. Reverse Vowels of a String

On this page

IntitutionComplexityCode