Member-only story
Count the Number of Triplets in an Array with Sum within the Given Range [a, b] | Coding Interview | Sorting
This is a medium category problem, and it should serve as a simple introduction to some other techniques for solving problems. And It has been asked by Amazon and SAP Labs.
For a better grasp of the problem, try to code the solution yourself. I have provided the code (properly commented) for reference if you get stuck at any point.
This article is part of the 30 Days Preparation plan for Coding Interviews 😎.
Table of Contents
Description
Given an array of N integers and a range [a, b], find the number of triplets from the given array with sum within the range.
In other words, the sum of all triplets should be greater or equal to a and lesser or equal to b.
Example 1:
Input: [4 8 6 3 2 7], range: [6 12]
Output: 4Explanation: The 4 triplets are [4 6 2], [4 3 2], [6 3 2], and
[3 2 7].Example 2:
Input: [7 4 2 9], range: [14 15]
Output: 1