← Deloitte bank

Deloitte · Question 21

Remove Element

Javacode⏱ O(n)💾 O(1)
Service-based

Problem

Remove all occurrences of a given value in-place.

Approach

Compact survivors forward.

Time O(n)Space O(1)

How it works

  1. 1Copy every non-val element forward.

Sample input / output

Input:
nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2
Output:
5

Constraints

0 <= nums.length <= 100.

Solution — read it, then walk it

Time O(n)Space O(1)Loops 1Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intremoveElement(int[] nums,int val)DEFINE j = 0for (int n : nums)if (n != val)nums[j++] = nRETURN jDEFINE static voidmain(String[] args)System.out.println(removeElement(newint[]{0, 1, 2, 2, 3, 0, 4,2}, 2))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/11

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits