Java Data Structures - Java List - Hackerrank Solution

 For this problem, we have  types of queries you can perform on a List:

  1. Insert  at index :

    Insert
    x y
  2. Delete the element at index :

    Delete
    x

Given a list, , of  integers, perform  queries on the list. Once all queries are completed, print the modified list as a single line of space-separated integers.

Input Format

The first line contains an integer,  (the initial number of elements in ).
The second line contains  space-separated integers describing .
The third line contains an integer,  (the number of queries).
The  subsequent lines describe the queries, and each query is described over two lines:

  • If the first line of a query contains the String Insert, then the second line contains two space separated integers , and the value  must be inserted into  at index .
  • If the first line of a query contains the String Delete, then the second line contains index , whose element must be deleted from .

Constraints



  • Each element in is a 32-bit integer.

Output Format

Print the updated list  as a single line of space-separated integers.

Sample Input

5
12 0 1 78 12
2
Insert
5 23
Delete
0

Sample Output

0 1 78 12 23

Explanation

 Insert 23 at index .

 Delete the element at index .

Having performed all  queries, we print  as a single line of space-separated integers.


Solution

import java.io.*;
import java.util.*;

class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Enter number of elements for List
        int n = sc.nextInt();
        ArrayList<Integer> list = new ArrayList<Integer>();

        // Adding elements to the list
        for (int i = 0; i < n; i++) {
            list.add(sc.nextInt());
        }

        // Getting no of queries
        int q = sc.nextInt();

        // Performing all the queries
        for (int i = 0; i < q; i++) {
            String queryType = sc.next();
            if(queryType.equals("Insert")){
                int index = sc.nextInt();
                int value = sc.nextInt();
                list.add(index, value);
            }else if(queryType.equals("Delete")){
                int index = sc.nextInt();
                list.remove(index);
            }
        }

        String resString = Arrays.toString(list.toArray());
        resString = resString.replaceAll(",","");
        resString = resString.substring(1,resString.length()-1);
        System.out.println(resString);
    }
}


Comments

Popular posts from this blog

Hackerrank - Quicksort 2 - Sorting

Hackerrank - Day of the Programmer

Hackerrank - UNIQUE ARMSTRONG NUMBER