Leetcode 2766: Relocate Marbles

grid47
grid47
Exploring patterns and algorithms
Feb 4, 2024 6 min read

You are given a 0-indexed integer array ’nums’ representing the initial positions of marbles. You are also provided with two arrays, ‘moveFrom’ and ‘moveTo’, where each step moves marbles from one position to another. After performing all the moves, return the sorted list of unique positions that have at least one marble.
Problem
Approach
Steps
Complexity
Input: The input consists of the following arrays: nums (the initial marble positions), moveFrom (the positions from which marbles are moved), and moveTo (the positions to which marbles are moved).
Example: nums = [4, 5, 6, 7], moveFrom = [4, 7, 5], moveTo = [6, 8, 7]
Constraints:
• 1 <= nums.length <= 10^5
• 1 <= moveFrom.length <= 10^5
• moveFrom.length == moveTo.length
• 1 <= nums[i], moveFrom[i], moveTo[i] <= 10^9
Output: Return the sorted list of unique positions where at least one marble exists after all moves are completed.
Example: For nums = [4, 5, 6, 7], moveFrom = [4, 7, 5], moveTo = [6, 8, 7], the output is [6, 7, 8].
Constraints:
• The output is a list of unique positions sorted in ascending order.
Goal: The goal is to track all the positions where marbles are placed after each move and return the sorted list of unique positions.
Steps:
• Create a set to store all occupied positions initially using the nums array.
• For each move, transfer marbles from moveFrom[i] to moveTo[i], updating the set of occupied positions.
• Finally, sort and return the positions.
Goal: The constraints ensure that the problem handles arrays of sizes up to 10^5 efficiently.
Steps:
• 1 <= nums.length <= 10^5
• 1 <= moveFrom.length <= 10^5
• moveFrom.length == moveTo.length
• 1 <= nums[i], moveFrom[i], moveTo[i] <= 10^9
Assumptions:
• There will always be at least one marble in the positions specified by moveFrom during the corresponding move.
Input: For nums = [4, 5, 6, 7], moveFrom = [4, 7, 5], moveTo = [6, 8, 7]
Explanation: Initially, the marbles are at positions [4, 5, 6, 7]. After each move, the marbles are relocated as described in the example. The final occupied positions are [6, 7, 8].

Input: For nums = [2, 3, 3, 6], moveFrom = [3, 2], moveTo = [4, 5]
Explanation: Initially, the marbles are at positions [2, 3, 3, 6]. After each move, the marbles are relocated, and the final occupied positions are [4, 5, 6].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus