Leetcode 2899. Last Visited Integers
Problem Statement
Given an array arr
and an integer k
, you need to modify the array such that for every integer i
in the array, if i
has been visited more than k
times in the past, you do not include it in the resulting array. The output should be the modified array.
Clarifying Questions
- Input Constraints:
- What is the range of values for the elements in the array?
- What is the length of the input array?
- Output Requirements:
- Should the order of elements in the modified array be the same as the input array?
- If no elements remain after filtering, should we return an empty array?
- Edge Cases:
- How should we handle negative values or zeroes if they are present in the array?
- What should be done if
k
is zero or negative?
For this problem, let’s assume:
- The array can contain both positive and negative integers.
- The integers can be in the range of typical 32-bit signed integers.
- The length of the input array can be up to (10^5).
- We should maintain the order of the elements in the modified array.
Strategy
To solve this problem:
- Use a hash map (unordered_map in C++) to maintain the count of each element.
- Iterate over the array and use the hash map to keep track of how many times each element has been seen.
- Only append elements to the result if their count in the hash map is less than or equal to
k
.
Code
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> lastVisitedIntegers(const vector<int>& arr, int k) {
unordered_map<int, int> count_map;
vector<int> result;
for (int num : arr) {
// Increase the count for the number
count_map[num]++;
// Only add to result if the count is less than or equal to k
if (count_map[num] <= k) {
result.push_back(num);
}
}
return result;
}
Time Complexity
- Time Complexity: (O(n)), where (n) is the length of the array. This is because we make a single pass through the array to count elements and construct the result.
- Space Complexity: (O(n)) in the worst case, for storing counts in the hash map and results in the vector.
This solution ensures efficient processing and maintains the order of elements as required.
Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?