Sound Story

. . . . . . . . . . . . .. “Sound Story” is published by Karl John Brillantes.

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Contains Duplicate III

Given an array of integers, find out 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.

This problem is extremely tricky. Obviously we can do it in brute force in time o(nk)

The solution uses bucket sort technique . It is very useful technique when we need to dabble in range of numbers

The basic principle of the bucket sort is that it maps the numbers between 0 and the bucket width to the same bucket . say if we have a bucket width of 3 then this will map 0 , 1 , 2 to the same bucket

Now depending upon this we need to find two indices k distance apart such that the difference between them is t

We create a bucket of width t + 1 where t is the required sum . This will mean that an array element with bucket index between 0 .. t will go in the same bucket

so if we encounter a bucket which is already filled then clearly we have two indices whose array difference is less than t

but what if we get a bucket index say t in one bucket and we get index t in the next bucket or index t in the previous bucket then also we get two indices where the difference between the element is less than or equal to t

so the gist is if we get a number with bucket index b and if it is already filled or its neighboring buckets are filled we get our answer

Add a comment

Related posts:

The Astonishing Story of Constantine and Maria of Lop Buri

A Greek man once almost became a the King of Siam, and some of the most cherished Thai desserts were invented by his wife. Believe me? When taking the Bangkok <> Chiang Mai train, your carriage will…

Size does not matter!

Size does not matter!, a Medium series by Miles Kubheka

Introducing the Local Needs Databank

by Georgia Iacovou on behalf of Turn2us. This has been cross-posted from the Data Collective, a community of people in social change organisations who use data. The Local Needs Databank is an open…