#3080
Mark Elements on Array by Performing Queries
MediumArrayHash TableSortingHeap (Priority Queue)SimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log k) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + m log k)Space O(n)
By sorting the array and using a priority queue, we can efficiently find the smallest unmarked elements. This reduces the need to repeatedly scan the array.
⚙️
Algorithm
3 steps- 1Step 1: Create a list of tuples containing each element and its index, then sort this list based on the element values.
- 2Step 2: Use a priority queue to track the smallest unmarked elements.
- 3Step 3: For each query, mark the specified index and then mark the next k smallest unmarked elements from the priority queue.
solution.py32 lines
1# Full working Python code
2import heapq
3
4def markElements(nums, queries):
5 n = len(nums)
6 marked = [False] * n
7 results = []
8 total_sum = sum(nums)
9 sorted_nums = sorted((num, i) for i, num in enumerate(nums))
10 min_heap = []
11
12 for num, index in sorted_nums:
13 heapq.heappush(min_heap, (num, index))
14
15 for index, k in queries:
16 if not marked[index]:
17 marked[index] = True
18 total_sum -= nums[index]
19 count = 0
20 while count < k and min_heap:
21 num, idx = heapq.heappop(min_heap)
22 if not marked[idx]:
23 marked[idx] = True
24 total_sum -= num
25 count += 1
26 results.append(total_sum)
27 return results
28
29# Example usage
30nums = [1, 2, 2, 1, 2, 3, 1]
31queries = [[1, 2], [3, 3], [4, 2]]
32print(markElements(nums, queries))ℹ
Complexity note: The sorting step takes O(n log n), and for each query, we may need to process up to k elements from the priority queue, leading to a logarithmic factor for each query.
- 1Sorting helps in efficiently finding the smallest elements.
- 2Using a priority queue allows for quick access to the smallest unmarked elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.