Mastering List Operations in Java with ArrayList

🚀 Java Practice Problem: Mastering List Operations (Insert & Delete) Here’s a classic problem I recently worked on — perfect for students learning Java Collections and preparing for coding interviews 👇 💡 Problem Statement You are given a list of integers. You need to perform multiple queries of two types: 🔹 Insert x y → Insert value y at index x 🔹 Delete x → Delete element at index x After performing all queries, print the updated list. 🧠 Key Learning Many students try solving this using arrays ❌ But the correct approach is to use ArrayList ✅ 👉 Why? Dynamic size Easy insert & delete Cleaner and efficient code ✅ Solution Approach ✔ Read input list ✔ Loop through queries ✔ Use: list.add(index, value) for Insert list.remove(index) for Delete 💻 Java Code import java.util.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int L = scanner.nextInt(); ArrayList<Integer> list = new ArrayList<>(); for(int i = 0; i < L; i++) { list.add(scanner.nextInt()); } int Q = scanner.nextInt(); for(int i = 0; i < Q; i++) { String query = scanner.next(); if(query.equals("Insert")) { int index = scanner.nextInt(); int value = scanner.nextInt(); list.add(index, value); } else if(query.equals("Delete")) { int index = scanner.nextInt(); list.remove(index); } } for(int num : list) { System.out.print(num + " "); } } } 📌 Sample Input 5 12 0 1 78 12 2 Insert 5 23 Delete 0 📌 Output 0 1 78 12 23 🎯 Teaching Insight As a trainer, I always emphasize: 👉 Choose the right data structure before coding 👉 Understand problem pattern (CRUD operations) 👉 Focus on clean and readable code 💬 Try this problem and let me know — did you first think of arrays or ArrayList? #Java #JavaProgramming #ArrayList #CodingPractice #LearnToCode #Programming #JavaTrainer #CodingInterview #TechEducation

To view or add a comment, sign in

Explore content categories