Minimum Index Distance Between Two Values
Updated
Problem statement
You are given an integer array nums and two different integers x and y. Each of them appears at least once in nums.
Pick an index i where nums[i] = x and an index j where nums[j] = y. Their distance is |i - j|. Return the smallest distance you can get.
Function
minimumIndexDistance(nums: int[], x: int, y: int) → intExamples
Example 1
nums = [3,5,4,2,6,5,6,6,5,4,8,3]x = 3y = 6return = 4One closest pair uses index 0, which holds x, and index 4, which holds y. Their distance is 4. No pair is closer, so that is the answer.
Example 2
nums = [1,2,1,2]x = 1y = 2return = 1Values 1 and 2 sit at indices next to each other, such as the first two positions. Their distance is one, the smallest possible, so that is the answer.
Constraints
2 <= nums.length <= 10^5.-10^9 <= nums[i], x, y <= 10^9.x != y, and both values occur at least once.
More Dream11 Onsite Interview questions
Similar questions at other companies
- Count Distinct Pairs With Sum KeBay · ONSITE INTERVIEWeBay interview questions
- Best Time to Buy and Sell StockAmazon · ONSITE INTERVIEW
- Bad Request AlertsMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Confusing Bib NumbersVerily · ONSITE INTERVIEW
- Group Transactions by HourAffirm · ONSITE INTERVIEWAffirm interview questions
- Longest Common PrefixKotak Mahindra Bank · PHONE SCREEN · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Rotate a Matrix by 90 DegreesIDFC Bank · ONSITE INTERVIEWIDFC Bank interview questions
- Plus OneDruva · ONSITE INTERVIEW
- Rotate a Flat Image ClockwiseGoogle · ONSITE INTERVIEWGoogle interview questions
- Merge Sorted ArrayDP World · ONSITE INTERVIEW