Skip to content

645. Set Mismatch 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<int> findErrorNums(vector<int>& nums) {
    int duplicate;

    for (const int num : nums)
      if (nums[abs(num) - 1] < 0)
        duplicate = abs(num);
      else
        nums[abs(num) - 1] *= -1;

    for (int i = 0; i < nums.size(); ++i)
      if (nums[i] > 0)
        return {duplicate, i + 1};

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[] findErrorNums(int[] nums) {
    int duplicate = 0;

    for (final int num : nums) {
      if (nums[Math.abs(num) - 1] < 0)
        duplicate = Math.abs(num);
      else
        nums[Math.abs(num) - 1] *= -1;
    }

    for (int i = 0; i < nums.length; ++i)
      if (nums[i] > 0)
        return new int[] {duplicate, i + 1};

    throw new IllegalArgumentException();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def findErrorNums(self, nums: list[int]) -> list[int]:
    for num in nums:
      if nums[abs(num) - 1] < 0:
        duplicate = abs(num)
      else:
        nums[abs(num) - 1] *= -1

    for i, num in enumerate(nums):
      if num > 0:
        return [duplicate, i + 1]