Algorithm


Problem Name: Java List

Problem Link: https://www.hackerrank.com/challenges/java-list/problem?isFullScreen=true

In this HackerRank Functions in Java programming problem solution,

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

  1. Insert y at index x:
    Insert
    x y
  2. Delete the element at index x:
    Delete
    x

Given a list, L of N integers, perform Q 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, N (the initial number of elements in L).
The second line contains N space-separated integers describing L.
The third line contains an integer, Q (the number of queries).
The 2Q 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 x y and the value y must be inserted into L at index X.
  • If the first line of a query contains the String Delete , then the second line contains index x, whose element must be deleted from L.

Constraints

  • 1 <= N <= 4000
  • 1 <= Q <= 4000
  • Each element in is a 32-bit integer.

Output Format

Print the updated list L 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

 

 

 

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        LinkedList < Integer> list = new LinkedList<>();
        for(int i = 0; i  <  n; i++){
            int a = scan.nextInt();
            list.add(a);
        }
        
        int q = scan.nextInt();
        for(int i = 0; i  <  q; i++){
            String s = scan.next();
            if(s.equals("Insert")){
                int index = scan.nextInt();
                int v = scan.nextInt();
                list.add(index, v);
            }
            else{
                int index = scan.nextInt();
                list.remove(index);
            }
        }
        scan.close();
        
        for(Integer a : list){
            System.out.print(a + " ");
        }
        System.out.println();
    }
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Java 2D Array in Java solution in Hackerrank - Hacerrank solution Java
Next
[Solved] Java Map in Java solution in Hackerrank - Hacerrank solution Java