algoadvance

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

  1. Input Constraints:
    • What is the range of values for the elements in the array?
    • What is the length of the input array?
  2. 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?
  3. 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:

Strategy

To solve this problem:

  1. Use a hash map (unordered_map in C++) to maintain the count of each element.
  2. Iterate over the array and use the hash map to keep track of how many times each element has been seen.
  3. 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

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