#Coding9 Q: Move Zeros to the End (Two Pointer Technique – Java) Example: int[] arr = {0, 1, 0, 3, 12}; Output → {1, 3, 12, 0, 0} ✅ Two Pointer Technique (Optimal – O(n), O(1)) static void moveZeros(int[] arr) { int j = 0; // position to place next non-zero for(int i = 0; i < arr.length; i++) { if(arr[i] != 0) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j++; } } } How It Works i scans the entire array j tracks where the next non-zero should go When a non-zero is found → swap with index j Zeros automatically move toward the end Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) This approach is interview-preferred because it is efficient and preserves order. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
Move Zeros to End with Java Two Pointer Technique
More Relevant Posts
-
#Coding10 👉 Q: Remove Duplicates from a Sorted Array (Two Pointer Technique – Java). Example: int[] arr = {1, 1, 2, 2, 3, 4, 4}; Output → {1, 2, 3, 4} Count → 4 ✅ Two Pointer Technique (Optimal – O(n), O(1)) static int removeDuplicates(int[] arr) { if(arr.length == 0) return 0; int j = 1; // pointer for next unique position for(int i = 1; i < arr.length; i++) { if(arr[i] != arr[i - 1]) { arr[j] = arr[i]; j++; } } return j; // number of unique elements } How It Works Since the array is already sorted, duplicates are adjacent i scans the array j tracks the position to place the next unique element When a new element is found → place it at index j Complexity Analysis • Time Complexity → O(n) • Space Complexity → O(1) (In-place solution) Two-pointer pattern is extremely powerful for array problems. #DSA #Java #Arrays #TwoPointers #ProblemSolving #InterviewPrep #LearningInPublic #LinkedInDSA
To view or add a comment, sign in
-
You already know interfaces in Java. A Functional Interface is simply an interface with exactly one abstract method — nothing more. This constraint is intentional and it allows Java to represent behavior as a value. Runnable is a classic example. It defines a single contract: void run(); Because there is only one abstract method, the compiler can infer intent and accept a lambda as its implementation. Runnable task = () -> { System.out.println("Executing task for Anwer Sayeed"); }; The lambda doesn’t replace Runnable. It implements its contract, concisely. This design choice is what enabled Java’s functional style without breaking its object-oriented foundations. #Java #FunctionalInterface #Runnable #LambdaExpressions #JavaDeveloper #CleanCode #Multithreading
To view or add a comment, sign in
-
⚠️ Java Autoboxing: Small Syntax, Big Memory Impact Autoboxing Can Quietly Kill Your Performance in Java Most developers don’t realize this: Long sum = 0L; for (long i = 0; i < 1_000_000; i++) sum += i; Looks harmless, right? It isn’t. That line inside the loop does this: sum = Long.valueOf(sum.longValue() + i); Every iteration: Unboxing (longValue()) Addition Boxing (Long.valueOf) New object allocation You just created 1 million Long objects,That means: Extra heap allocations More GC pressure Slower execution Worse cache locality The correct version: long sum = 0L; for (long i = 0; i < 1_000_000; i++) sum += i; Zero allocations. Fully optimized by the JIT. 🔎 Rule of Thumb Use primitives in: Tight loops Counters Aggregations Performance-critical paths Autoboxing is syntactic sugar but under load, sugar becomes poison. #Java #JVM #Autoboxing #PerformanceEngineering #BackendDevelopment #JavaPerformance #CleanCode #SoftwareEngineering #GarbageCollection #LowLatency #HighPerformance #TechDeepDive #LearnInPublic
To view or add a comment, sign in
-
In Part 4 of Magnus Smith’s Functional Optics for Modern Java series, he explores traversals and pattern rewrites. Learn how the Focus DSL’s TraversalPath makes navigating and composing collections in Java more readable, fluent, and powerful. 🔗 Read more: https://buff.ly/DszWTCN #Java #FunctionalProgramming #DSL #SoftwareEngineering #CodeOptimisation #TechInsights
To view or add a comment, sign in
-
🚀Java practice - Day 87 Completed! 👍 Problem: Sum of Squares of Special Elements Language: Java Today’s problem was about identifying special elements in a 1-indexed array. An element is considered special if its index divides the length of the array (n % i == 0). The task was to calculate the sum of the squares of such elements.✨ #Day87 #Java #LeetCode #Arrays #ProblemSolving #DailyCoding #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
Monday Deep Dive – Java Strings Complete Revision Today I revisited one of the most important topics in Core Java: 🔹 String & String Constant Pool 🔹 Immutability & Memory Management 🔹 String Comparison Techniques 🔹 Concatenation Methods & Performance Tests 🔹 substring(), split(), indexOf() 🔹 String vs StringBuffer vs StringBuilder 🔹 Immutable Class Design 🔹 toString() Method 🔹 StringTokenizer (Legacy vs Modern Approach) Understanding how Strings work internally is crucial for writing efficient, optimized, and interview-ready Java code. Strong fundamentals. Clean code. Better performance. 🚀 #Java #CoreJava #JavaDeveloper #DSA #StringConcepts #Coding #LearningJourney #CodesInTransit #InterviewPreparation #MondayMotivation #RevisitingTheTopics
To view or add a comment, sign in
-
Quick Java Tip 💡: Labeled break (Underrated but Powerful) Most devs know break exits the nearest loop. But what if you want to exit multiple nested loops at once? Java gives you labeled break 👇 outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; // exits BOTH loops } } } ✅ Useful when: Breaking out of deeply nested loops Avoiding extra flags/conditions Writing cleaner logic in algorithms ⚠️ Tip: Use it sparingly — great for clarity, bad if overused. Small features like this separate “knows Java syntax” from “understands Java flow control.” #Java #Backend #DSA #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
-
🚀 Quick Sort in Java Quick Sort uses Divide & Conquer — Pick a pivot ➝ Partition ➝ Recursively sort. ⚡ Avg Time: O(n log n) 🔥 Fast & efficient for large datasets static void quickSort(int arr[], int low, int high) { if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } Clean. Powerful. Classic. 💻✨ #Java #QuickSort #Coding #DSA
To view or add a comment, sign in
-
🚀 Day 5/30 – Java DSA Challenge 🔎 Problem 41: 209. Minimum Size Subarray Sum (LeetCode – Medium) Another powerful Sliding Window (Variable Size) problem 🔥 🧠 Problem Summary Given: An array of positive integers A target value 🎯 Return the minimum length of a contiguous subarray whose sum ≥ target. If no such subarray exists → return 0. 💡 Key Insight Since all numbers are positive, we can safely use: ✅ Variable Sliding Window Why? Because: Expanding window → sum increases Shrinking window → sum decreases No negative values to break logic 🔄 Approach 1) Expand right pointer → keep adding to sum 2) When sum ≥ target → -Update minimum length -Shrink from left to find smaller valid window 3) Continue until end ⏱ Time Complexity ✅ O(n) Each element is added and removed at most once. 📦 Space Complexity ✅ O(1) No extra data structures used. 🎯 Pattern Name Variable Size Sliding Window Minimum Window with Condition Shrink When Valid Pattern 🔥 41 Problems Completed Day 5 = Full Sliding Window Mastery 💪 Today covered: At most K distinct Fixed window Variable window Frequency matching Minimum window condition Serious progress 🚀 #Day5 #30DaysOfCode #Java #DSA #LeetCode #SlidingWindow #TwoPointers #InterviewPrep #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Splitting Strings: String.split() (Java) The `String.split()` method in Java allows you to split a string into an array of substrings based on a delimiter. The delimiter can be a single character or a regular expression. The `split()` method is useful for parsing strings, extracting data from structured text, and processing command-line arguments. It returns an array of strings representing the substrings. #Java #JavaDev #OOP #Backend #professional #career #development
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development