Week 10: Assorted Problems
1) Minimum Number of Moves (111/211)
You are given two integer arrays (arr1 and arr2), both with length n. Return the smallest number of moves needed to transform arr2 into arr1.
A move is defined to be adding or subtracting 1 from any value in arr2.
The elements within arr2 can be rearranged to whatever order you want (and does not count as a move).
Input: seats = [3,1,5], students = [2,7,4]
Output: 4
Explanation: The students are moved as follows:
- The first student is moved from from position 2 to position 1 using 1 move.
- The second student is moved from from position 7 to position 5 using 2 moves.
- The third student is moved from from position 4 to position 3 using 1 move.
In total, 1 + 2 + 1 = 4 moves were used.
Input: seats = [2,2,6,6], students = [1,3,2,6]
Output: 4
Explanation: The students are moved as follows:
- The first student is moved from from position 1 to position 2 using 1 move.
- The second student is moved from from position 3 to position 6 using 3 moves.
- The third student is not moved.
- The fourth student is not moved.
In total, 1 + 3 + 0 + 0 = 4 moves were used.
Time Complexity: O(nlgn) // Can be O(n) if you know the maximum element value and use O(n) sorts
Space Complexity: O(n)
2) Two Out of Three
Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order. Only values between 1 and 100 will be present.
Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]
Output: [3,2]
Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]
Output: [2,3,1]
Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]
Output: []
Time Complexity: O(n)
Space Complexity: O(n)
3) Middle Index in Array
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).
A middleIndex is an index where nums[0] + nums[1] + … + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + … + nums[nums.length-1].
If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.
Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Input: nums = [2,3,-1,8,4]
Output: 3
Explanation:
The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
The sum of the numbers after index 3 is: 4 = 4
Input: nums = [1,-1,4]
Output: 2
Explanation:
The sum of the numbers before index 2 is: 1 + -1 = 0
The sum of the numbers after index 2 is: 0
Input: nums = [2,5]
Output: -1
Explanation:
There is no valid middleIndex.
Input: nums = [1]
Output: 0
Explantion:
The sum of the numbers before index 0 is: 0
The sum of the numbers after index 0 is: 0
Time Complexity: O(n)
Space Complexity:n O(1)