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

Publicado em: 22 Agosto 2024
no canal de: 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`.


Nesta página do site você pode assistir ao vídeo on-line Python Interview Question 42 - Given an integer array `nums` and an integer `k`, return `true` if duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário TutorialShore 22 Agosto 2024, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 30 vezes e gostou 1 espectadores. Boa visualização!