|
| 1 | +## Rotate And Delete |
| 2 | +Given an array arr[] of N integers. Do the following operation n-1 times. For every Kth operation: |
| 3 | + |
| 4 | +> Right rotate the array clockwise by 1. |
| 5 | +> Delete the (n-k+1)th last element. |
| 6 | +> Now, find the element which is left at last. |
| 7 | +
|
| 8 | +**Input:** |
| 9 | + |
| 10 | +The first line of input contains an integer T denoting the number of test cases. Then T test cases follows. Each test case contains two lines. The first line of each test case contains an integer N. Then in the next line are N space separated values of the array arr[]. |
| 11 | + |
| 12 | +**Output:** |
| 13 | + |
| 14 | +For each test case in a new line print the required result. [🔗Goto](https://practice.geeksforgeeks.org/problems/rotate-and-delete-1587115621/1/?page=2&difficulty[]=1&status[]=unsolved&category[]=Arrays&category[]=Strings&sortBy=accuracy#) |
| 15 | + |
| 16 | +<details> |
| 17 | +<summary>Full Code</summary> |
| 18 | + |
| 19 | +```java |
| 20 | +import java.io.*; |
| 21 | +import java.util.*; |
| 22 | + |
| 23 | +class Main { |
| 24 | + |
| 25 | + public static void main (String[] args) throws IOException { |
| 26 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 27 | + int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases |
| 28 | + |
| 29 | + while(t-->0){ |
| 30 | + int n = Integer.parseInt(br.readLine().trim()); |
| 31 | + ArrayList<Integer> arr = new ArrayList<Integer>(n); |
| 32 | + String inputLine[] = br.readLine().trim().split(" "); |
| 33 | + for(int i=0; i<n; i++){ |
| 34 | + arr.add(Integer.parseInt(inputLine[i])); |
| 35 | + } |
| 36 | + |
| 37 | + Solution ob = new Solution(); |
| 38 | + |
| 39 | + System.out.println(ob.rotateDelete(arr, n)); |
| 40 | + |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +``` |
| 46 | +</details> |
| 47 | + |
| 48 | +```java |
| 49 | +class Solution{ |
| 50 | + public static int rotateDelete(ArrayList<Integer> ar, int n){ |
| 51 | + for(int i = 1; i < n; ++i){ |
| 52 | + int temp = ar.get((ar.size() - 1)); |
| 53 | + ar.add(0 , temp); |
| 54 | + ar.remove((ar.size() - 1)); |
| 55 | + if((ar.size() - i) < 0) |
| 56 | + ar.remove(0); |
| 57 | + else |
| 58 | + ar.remove(ar.size() - i); |
| 59 | + } |
| 60 | + return ar.get(0); |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
0 commit comments