Skip to content

2766. Relocate Marbles 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<int> relocateMarbles(vector<int>& nums, vector<int>& moveFrom,
                              vector<int>& moveTo) {
    set<int> numsSet{nums.begin(), nums.end()};

    for (int i = 0; i < moveFrom.size(); ++i) {
      numsSet.erase(numsSet.find(moveFrom[i]));
      numsSet.insert(moveTo[i]);
    }

    return {numsSet.begin(), numsSet.end()};
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public List<Integer> relocateMarbles(int[] nums, int[] moveFrom, int[] moveTo) {
    Set<Integer> numsSet = Arrays.stream(nums).boxed().collect(Collectors.toSet());

    for (int i = 0; i < moveFrom.length; ++i) {
      numsSet.remove(moveFrom[i]);
      numsSet.add(moveTo[i]);
    }

    return numsSet.stream().sorted().toList();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def relocateMarbles(
      self,
      nums: list[int],
      moveFrom: list[int],
      moveTo: list[int],
  ) -> list[int]:
    numsSet = set(nums)

    for f, t in zip(moveFrom, moveTo):
      numsSet.remove(f)
      numsSet.add(t)

    return sorted(numsSet)