Source : https://www.hackerrank.com/challenges/dynamic-array
- Create a list, , of empty sequences, where each sequence is indexed from to . The elements within each of the sequences also use -indexing.
- Create an integer, , and initialize it to .
- The types of queries that can be performed on your list of sequences () are described below:
- Query:
1 x y- Find the sequence, , at index in .
- Append integer to sequence .
- Query:
2 x y- Find the sequence, , at index in .
- Find the value of element in (where is the size of ) and assign it to .
- Print the new value of on a new line
- Query:
Task
Given , , and queries, execute each query.
Note: is the bitwise XOR operation, which corresponds to the ^ operator in most languages. Learn more about it on Wikipedia.
Input Format
The first line contains two space-separated integers, (the number of sequences) and (the number of queries), respectively.
Each of the subsequent lines contains a query in the format defined above.
Constraints
- It is guaranteed that query type will never query an empty sequence or index.
Output Format
For each type query, print the updated value of on a new line.
Sample Input
2 51 0 51 1 71 0 32 1 02 1 1Sample Output
73Explanation
Initial Values:
= [ ]
= [ ]
Query 0: Append to sequence .
= [5]
= [ ]
Query 1: Append to sequence .
= [5]
= [7]
Query 2: Append to sequence .
= [5, 3]
= [7]
Query 3: Assign the value at index of sequence to , print .
= [5, 3]
= [7]
7Query 4: Assign the value at index of sequence to , print .
= [5, 3]
= [7]
3Source : https://www.hackerrank.com/challenges/dynamic-array
Solution
| // Karthikalapati.blogspot.com | |
| import java.util.Scanner; | |
| import java.util.ArrayList; | |
| public class Solution { | |
| public static void main(String[] args) { | |
| Scanner scan = new Scanner(System.in); | |
| int N = scan.nextInt(); | |
| int Q = scan.nextInt(); | |
| int lastAns = 0; | |
| /* Create 2-D ArrayList */ | |
| ArrayList<ArrayList<Integer>> lists = new ArrayList(); | |
| for (int i = 0; i < N; i++) { | |
| lists.add(new ArrayList<Integer>()); | |
| } | |
| /* Perform Q Queries */ | |
| for (int i = 0; i < Q; i++) { | |
| int q = scan.nextInt(); | |
| int x = scan.nextInt(); | |
| int y = scan.nextInt(); | |
| ArrayList<Integer> seq = lists.get((x ^ lastAns) % N); | |
| if (q == 1) { | |
| seq.add(y); | |
| } else if (q == 2) { | |
| lastAns = seq.get(y % seq.size()); | |
| System.out.println(lastAns); | |
| } | |
| } | |
| scan.close(); | |
| } | |
| } |
No comments:
Post a Comment