LeetCode - Blind 75 - Contains Duplicate

The Problem Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example Input: nums = [1,2,3,1] Output: true Explanation: The element 1 occurs at indices 0 and 3. Follow-up: Can you come up with an algorithm that has less than O(NlogN) time complexity? Brute Force Solution func containsDuplicate(_ nums: [Int]) -> Bool { var nums = nums let N = nums.count if N == 0 { return false } nums.sort() var prev = nums[0] for i in 1 ..< N { let num = nums[i] if num == prev { return true } else { prev = num } } return false } Explanation The brute force solution for this problem uses sorting to allow us to quickly detect duplicates since identical elements will be adjacent. After sorting, it iterates through all elements, checking if the current element is equal to the previous one; if it is, it returns true immediately. If not, it updates prev. If no duplicates are detected, it returns false. ...

October 26, 2024 · 2 min · Dmytro Chumakov

LeetCode - Blind 75 - Two Sum

The Problem Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to the target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. Follow-up: Can you come up with an algorithm that has less than O(N^2) time complexity? ...

October 25, 2024 · 2 min · Dmytro Chumakov