Skip to content

2113. Elements in Array After Removing and Replacing Elements 👍

  • Time: $O(q)$
  • Space: $O(q)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  vector<int> elementInNums(vector<int>& nums, vector<vector<int>>& queries) {
    vector<int> ans;

    for (const vector<int>& query : queries) {
      const int time = query[0];
      const int index = query[1];
      ans.push_back(f(nums, time % (2 * nums.size()), index));
    }

    return ans;
  }

 private:
  int f(const vector<int>& A, int time, int index) {
    const int n = A.size();
    if (time < n) {  // [0, 1, 2] -> [1, 2] -> [2]
      index += time;
      return index >= n ? -1 : A[index];
    } else {  // [] -> [0] -> [0, 1]
      return index >= time - n ? -1 : A[index];
    }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int[] elementInNums(int[] nums, int[][] queries) {
    int[] ans = new int[queries.length];

    for (int i = 0; i < queries.length; ++i) {
      final int time = queries[i][0];
      final int index = queries[i][1];
      ans[i] = f(nums, time % (2 * nums.length), index);
    }

    return ans;
  }

  private int f(int[] A, int time, int index) {
    final int n = A.length;
    if (time < n) { // [0, 1, 2] -> [1, 2] -> [2]
      index += time;
      return index >= n ? -1 : A[index];
    } else { // [] -> [0] -> [0, 1]
      return index >= time - n ? -1 : A[index];
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def elementInNums(
      self,
      nums: list[int],
      queries: list[list[int]],
  ) -> list[int]:
    n = len(nums)

    def f(time: int, index: int) -> int:
      if time < n:  # [0, 1, 2] -> [1, 2] -> [2]
        index += time
        return -1 if index >= n else nums[index]
      else:  # [] -> [0] -> [0, 1]
        return -1 if index >= time - n else nums[index]

    return [f(time % (2 * n), index) for time, index in queries]