Skip to main content

Move Zeroes - DSA Day11

Java · DSA · Two Pointers

Push every 0 to the end of an array while keeping the other values in their original order, in place, with no extra array. Watch the two pointers i and k rearrange it step by step.

01 The problem

Given an array of N integers, move all the zeros to the end. The non-zero values must keep their relative order, and you should change the array in place.

For [0, 1, 0, 3, 12] the answer is [1, 3, 12, 0, 0]. The order 1 → 3 → 12 is unchanged.

Type an array to see what the program prints.

02 The code

Two loops and one extra variable. k is the next position where a non-zero value should go. The first loop packs the non-zeros to the front, and the second loop fills the rest with zeros.

package Day11;

import java.util.Scanner;

public class MoveZeroes {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n= sc.nextInt();

        int[] arr=new int[n];
        for (int i = 0; i < arr.length ; i++) {
            arr[i]= sc.nextInt();
        }
        int k = 0;
        for (int i = 0; i < arr.length; i++) {
                if (arr[i]==0){
                    continue;
                }else {
                    arr[k]=arr[i];
                    k++;
                }
        }
                for (int i=k;i<= arr.length-1;i++){
                    arr[i]=0;
                }
        for (int el:arr){
            System.out.print(el+" ");
        }
    }
}

03 How it works

1

k is the write pointer

It starts at 0 and always points to the next slot that should hold a non-zero value.

2

i is the read pointer

It scans every element once, from left to right.

3

Zero? Skip it

continue leaves k where it is, so the gap stays open for the next non-zero.

4

Non-zero? Copy and advance

arr[k] = arr[i]; k++ packs it right after the previous non-zero, so the order is kept.

5

Fill the tail

After the first loop, k equals the number of non-zeros. Every slot from k to the end becomes 0.

6

Safe to overwrite

k never gets ahead of i, so the copy never overwrites a value that hasn't been read yet.

04 Live tracer

This runs the code above one step at a time. The array changes in place as you step.

๐ŸŽฌ Two-pointer tracer
Amber pointer = i (read), teal pointer = k (write). Violet cells are packed non-zeros, rose cells are filled zeros. Click any table row to jump to it.
i
k
arr[]
phase = –
i = –
k = 0
steps = 0
Load an array, then press Step ▶ to begin.
0 / 00%
Program printed–
Non-zeros kept in order–
Zeros moved to the end–
Speed
#PhaseikActionarr

05 Three ways to solve it

ApproachIdeaTimeExtra space
Extra arrayCopy the non-zeros into a new array, then pad it with zerosO(N)O(N)
Copy + fill (this post)Pack non-zeros to the front with k, then zero the tailO(N)O(1)
Swap in one passWhen arr[i] != 0, swap arr[i] with arr[k] and do k++O(N)O(1)

Copy + fill reads each element once in the first loop and touches only the N − k zero slots in the second, so the total is still O(N). The swap version does it in a single loop, but each swap writes two values.

06 Quick revision

1

Two pointers, one array

i reads, k writes. No second array is needed.

2

Order is preserved

Non-zeros are copied in the same left-to-right order they were read.

3

k counts the non-zeros

After loop 1, k = number of non-zeros, and n − k = number of zeros.

4

Fill from k to the end

i = k … n − 1 all become 0.

5

O(N) time, O(1) space

Each loop is linear, and the only extra variable is k.

6

Test the edge inputs

Try no zeros [1 2 3], all zeros [0 0 0], and zeros at the start.

07 Check yourself

Interactive reference for the "move zeroes" two-pointer pattern in Java-based DSA practice.

Comments

Popular posts from this blog

Get Keycloak Auth Access Token

Understanding Keycloak Auth Access Token – A Deep Dive $ keycloak / auth-deep-dive ๐Ÿ” Identity & Access Management Getting a Keycloak Access Token — and Actually Understanding It June 2025 Keycloak OAuth 2.0 JWT OpenID Connect Service Account You hit Keycloak's token endpoint, you get back a fat JSON blob — but what is all that stuff? This post dismantles a real token response piece by piece so you know exactly what you have, why the JWT is structured the way it is, and what to do with it next. ๐Ÿ“ก Step 1 — How to Get the Token Keycloak speaks OAuth 2.0 . The endpoint that issues tokens lives under your realm: HTTP Token Endpoint POST http://127.0.0.1:7080/realms/master/protocol/openid-connect/token Content-Type : application/x-www-form-urlencoded grant_type =client_credentials &client_id =eazybank-callcenter-cc ...

Observability & Monitoring through Loki,Promtail (Alloy),Prometheus,Micrometer in Grafana

๐Ÿ”ง What this demo covers End-to-end observability setup using Prometheus + Loki + Grafana Integration of Micrometer with Spring Boot for real-time metrics Log collection using Promtail / Alloy from application containers ๐Ÿ“Š Metrics Monitoring (Prometheus) Scraping metrics from /actuator/prometheus endpoint JVM metrics: memory, threads, GC activity HTTP metrics: request count, latency, error rates Custom metrics via Micrometer ๐Ÿ“œ Centralized Logging (Loki + Promtail) Aggregates logs from multiple microservices Label-based log filtering (fast & efficient) No heavy indexing → lightweight compared to ELK ๐Ÿ“ˆ Visualization (Grafana Dashboards) Real-time dashboards for metrics & logs Correlate logs with metrics for faster debugging Pre-built + custom dashboards ⚙️ Architecture Flow Spring Boot app → exposes metrics via Micrometer Prometheus → scrapes & stores metrics Promtail/Alloy → collects logs → pushes to Loki...

Setting Alerts , Notification Policies , Contact Points in Grafana

Grafana · Alerting Setting Up Alert Policies, Contact Points & Notification Policies in Grafana Published May 23, 2026  ·  14 min read  ·  Grafana 10+ A complete step-by-step guide to configuring Grafana's three pillars of alerting — alert rules, contact points, and notification policies — so your team gets the right alert, on the right channel, at the right time. Table of Contents 1. How Grafana Alerting Works 2. Prerequisites & Enabling Unified Alerting 3. Setting Up Contact Points 4. Configuring Email Contact Points 5. Configuring Webhook Contact Points 6. Other Contact Point Types 7. Creating Alert Rules (Alert Policies) 8. Setting Up Notification Policies 9. Mute Timings & Silences 10. Testing & Troubleshooting 11. Best Practices 1. How Grafana Alerting Works Grafana Unified Alerting has three core bui...