Rearrange Arrays Efficiently with Two Pointers in Java

Day 20 | Programming Classes at TAP Academy 🔄 Rearrange Arrays💥 💡 The Problem Given an array with positive numbers and -1s: 👉 Move all -1s to the beginning 👉 Keep it efficient (no extra space, no unnecessary loops) 🚨 Where most people go wrong Create a new array ❌ Traverse twice ❌ Focus on output, not efficiency ❌ That works… but ⚡ The Smarter Approach — Two Pointers Use two pointers (i, j) Traverse from the end Place non -1 elements correctly Fill remaining positions with -1 🧠 Core Idea If element is -1 → skip Else → move it to position j Reduce pointers Fill leftover indices with -1 💻 Code public static void rearrange(int[] arr) { int i = arr.length - 1; int j = arr.length - 1; while (i >= 0) { if (arr[i] == -1) { i--; } else { arr[j] = arr[i]; i--; j--; } } while (j >= 0) { arr[j] = -1; j--; } } 🔁 Same Pattern, Different Problem 👉 Move all 0s to the end public static void moveZeros(int[] arr) { int i = 0, j = 0; while (i < arr.length) { if (arr[i] == 0) { i++; } else { arr[j] = arr[i]; i++; j++; } } while (j < arr.length) { arr[j] = 0; j++; } } 🧠 What this really teaches This isn’t just arrays. It’s about: ✔️ Thinking before coding ✔️ Writing optimal logic ✔️ Understanding how data actually moves Also connects to a key concept: 👉 Arrays in Java are passed by reference, so changes reflect directly. #Java #DSA #ProblemSolving #InterviewPrep #Learning #Developers #Programming #Arrays #CoreJava #Upskilling #Coding #DSA #Problem #Thinking #TAPAcademy #Logics #Optimal

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories