Degree of an Array in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of non-negative integers called nums, the degree of this array is actually the maximum frequency of any one of its elements. We have to find the smallest possible length of a contiguous subarray of nums, that has the same degree as nums.

So, if the input is like [1,2,2,3,1], then the output will be 2, this is because the input array has a degree of 2 because both elements 1 and 2 appear twice. The subarrays that have the same degree − [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2] The shortest length is 2. So answer will be 2.

To solve this, we will follow these steps −

  • Define an array freq of size 50000 and fill this with 0
  • max_ := 0
  • for each n in nums
    • (increase freq[n] by 1)
    • max_ := maximum of max_ and freq[n]
  • fill freq array with 0.
  • min_ := size of nums
  • for initialize i := 0, j := -1, size := size of nums, when j < size, do −
    • if j >= 0 and freq[nums[j]] is same as max_, then −
      • min_ := minimum of min_ and j - i + 1
    • otherwise when j < size - 1, then −
      • increase j by 1
      • increase freq[nums[j]] by 1
    • Otherwise
      • Come out from the loop
  • return min_

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findShortestSubArray(vector<int>& nums) {
      vector<int> freq(50000, 0);
      int max_ = 0;
      for (const int n : nums)
         max_ = max(max_, ++freq[n]);
      fill(freq.begin(), freq.end(), 0);
      int min_ = nums.size();
      for (int i = 0, j = -1, size = nums.size(); j < size;) {
         if (j >= 0 && freq[nums[j]] == max_)
            min_ = min(min_, j - i + 1), --freq[nums[i++]];
         else if (j < size - 1)
            ++freq[nums[++j]];
         else
         break;
      }
      return min_;
   }
};
main(){
   Solution ob;
   vector<int> v = {1, 2, 2, 3, 1};
   cout << (ob.findShortestSubArray(v));
}

Input

{1, 2, 2, 3, 1}

Output

2
raja
Updated on 04-Jul-2020 09:43:10

Advertisements