Contains Duplicate III in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers, we have to check whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t. And the absolute difference between i and j is at most k. So if input is like [1,2,3,1], then if k = 3 and t = 0, then return true.

To solve this, we will follow these steps −

  • Make a set s, n := size of nums array

  • for i in range 0 to n – 1

    • x is index of set element starting from nums[i] and above

    • if x is not in range of the set and value of x <= nums[i] + t, then return true

    • if x is not the first element

      • x := next element as random

      • if t th element starting from x is >= nums[i], then return true

    • insert nums[i] into s, then delete nums[i - k] from s

  • return false


Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
      multiset <int> s;
      int n = nums.size();
      for(int i = 0; i< n; i++){
         multiset <int> :: iterator x = s.lower_bound(nums[i]);
         if(x != s.end() && *x <= nums[i] + t ) return true;
            if(x != s.begin()){
               x = std::next(x, -1);
               if(*x + t >= nums[i])return true;
            if(i >= k){
               s.erase(nums[i - k]);
         return false;
   Solution ob;
   vector<int> v = {1,2,3,1};
   cout << (ob.containsNearbyAlmostDuplicate(v, 3,0));




Updated on 02-May-2020 07:11:25