Rotate and delete
JavaView on GFG
Time: O(n^2)
Space: O(n)
Advertisement
Intuition
Alternating operations: rotate array and delete specific element. Simulate rounds.
Algorithm
- 1In each round i: rotate right by 1, delete element at position n-i (1-indexed). Repeat until one remains.
Common Pitfalls
- •Simulate O(n^2). Use deque for efficient rotation and deletion.
Rotate and delete.java
Java
// Approach: Simulate the process: rotate array and delete specified element per round.
// Time: O(n^2) Space: O(n)
class Solution {
public static int rotateDelete(ArrayList<Integer> arr) {
boolean flag = true;
int n = arr.size();
int x = n / 2;
while (x != 0) {
if (flag) {
n -= 1;
flag = false;
} else {
n -= 2;
flag = true;
}
x--;
}
return arr.get(n);
}
}Advertisement
Was this solution helpful?