Python Interview Question 42 - Given an integer array `nums` and an integer `k`, return `true` if

Published: 22 August 2024
on channel: TutorialShore
30
1

*Explanation:* `nums[2]` and `nums[3]` are both `1`, and the indices difference is `3 - 2 = 1`, which is equal to `k`.
*Output:* `True`

Scenario 3

*Input:* `nums = [1, 2, 3, 1, 2, 3]`, `k = 2`
*Explanation:* There are no pairs of duplicate elements where the indices difference is less than or equal to `k`.
*Output:* `False`

Explanation

Dictionary `index_map`

This dictionary keeps track of the last seen index of each element in the array.

Iteration over the Array

We iterate over the array using `enumerate()` to get both the index `i` and the value `num` at each step.
If the element `num` has been seen before (i.e., it exists in `index_map`), we check if the difference between the current index `i` and the last seen index `index_map[num]` is less than or equal to `k`.
If the condition is satisfied, the function returns `True`.

Updating the Dictionary

Whether or not a duplicate is found, we update the dictionary with the current index of the element.

Returning the Result

If no such pair of indices is found during the iteration, the function returns `False`.


On this page of the site you can watch the video online Python Interview Question 42 - Given an integer array `nums` and an integer `k`, return `true` if with a duration of hours minute second in good quality, which was uploaded by the user TutorialShore 22 August 2024, share the link with friends and acquaintances, this video has already been watched 30 times on youtube and it was liked by 1 viewers. Enjoy your viewing!