Leetcode 697. Degree of an Array
Given a non-empty array of non-negative integers nums
, the degree of this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray of nums
that has the same degree as nums
.
The strategy involves several steps:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
int findShortestSubArray(vector<int>& nums) {
unordered_map<int, int> freq, first, last;
int degree = 0, minLength = nums.size();
// Calculate frequency and track first and last occurrence
for (int i = 0; i < nums.size(); ++i) {
int num = nums[i];
if (first.find(num) == first.end()) {
first[num] = i;
}
last[num] = i;
freq[num]++;
degree = max(degree, freq[num]);
}
// Find the smallest subarray with the same degree
for (const auto& entry : freq) {
if (entry.second == degree) {
int num = entry.first;
int length = last[num] - first[num] + 1;
minLength = min(minLength, length);
}
}
return minLength;
}
int main() {
vector<int> nums = {1, 2, 2, 3, 1, 4, 2};
cout << "The length of the smallest subarray with the same degree is " << findShortestSubArray(nums) << endl;
return 0;
}
The time complexity of the solution is O(n), where n is the length of the input array.
Thus, the approach ensures efficient processing and meets typical constraints expected in coding interviews.
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?