1848. Minimum Distance to the Target Element
Problem Description
You are provided with an array of integers called nums
. Your task is to find an index i
where the value at that index (nums[i]
) is the same as the target
value provided. Additionally, you have a starting index start
, and you want to find the i
that is closest to start
. This means you want to minimize the absolute difference between start
and i
(abs(i - start)
). The final output should be the minimized absolute difference. It's important to note that it is confirmed that at least one instance of the target
value exists in the nums
array.
Intuition
The intuition behind the solution is to iterate over each element in the array and check if it matches the target
value. If it matches, we calculate the absolute difference between the current index i
and the start
index. We are interested in the minimum such difference, so we keep an ongoing record of the minimum difference calculated so far. This process involves a linear scan of the array and comparison of each element against the target
. As we are guaranteed that target
exists in the array, we do not need to handle cases where the target is absent. The solution approach is straightforward because the problem does not require us to optimize for time complexity beyond the linear scan, given the nature of the problem.
Solution Approach
The provided reference solution approach is a simple and direct method to solve the problem with time complexity O(n)
and space complexity O(1)
, where n
is the number of elements in nums
.
Here are the steps implemented in the solution:
-
Initialize a variable
ans
to hold the minimum distance found so far. It's initialized withinf
(infinity), which is a placeholder for the largest possible value. This ensures that the first comparison will always replaceinf
with a valid distance. -
Iterate through the input list
nums
using afor
loop. Theenumerate
function is used to get both the indexi
and the valuex
at each position in the list. -
For each element
x
and its corresponding indexi
, we check ifx
matches thetarget
. -
If a match is found, calculate the absolute difference between
i
and the givenstart
index:abs(i - start)
. -
Update
ans
to be the minimum of the currentans
and the newly calculated absolute difference. This step is the heart of the solution, as it maintains the smallest distance encountered as the loop progresses through the array. -
After the loop has finished examining all elements, return the value of
ans
. At this point,ans
contains the minimum absolute difference between thestart
index and an indexi
wherenums[i] == target
.
No additional data structures are needed, and pure iteration with basic comparisons are the only patterns used in this solution. This approach is the most optimal for this kind of problem where there isn't a pattern or structure that can be exploited to reduce the time complexity below O(n)
.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's consider a small example to illustrate the solution approach. Assume we have the following parameters:
nums = [4,3,2,5,3,5,1,2]
target = 3
start = 5
We want to find the index i
where nums[i]
is equal to the target value (3
), and which is closest to the start
index (5
). Following the solution steps:
-
We initialize
ans
toinf
. At this point,ans
would represent infinity and acts as a very high starting point for comparison. -
As we iterate over
nums
, we will compare each element with thetarget
:Loop iteration i
x
(value atnums[i]
)abs(i - start)
ans
1st 0 4 5 inf 2nd 1 3 4 4 (since 4 < inf) 3rd 2 2 3 4 (since 3 > 4) 4th 3 5 2 4 (since 2 > 4) 5th 4 3 1 1 (since 1 < 4) 6th 5 5 0 1 (since 0 > 1) 7th 6 1 1 1 (since 1 >= 1) 8th 7 2 2 1 (since 2 > 1) -
We check each time if
x == target
. When we find a match, we calculateabs(i - start)
. -
If a match is found:
- For
i = 1
,x = 3
, which matches thetarget
. We calculateabs(1 - 5) = 4
and updateans
to4
. - For
i = 4
,x = 3
again. We calculateabs(4 - 5) = 1
and updateans
to1
since1
is less than the currentans
of4
.
- For
-
We continue the process until we have iterated through the entire array. The minimum value encountered in
ans
is the one that will remain. -
After the loop has finished, we have found that the closest index with the target value
3
relative tostart
5
is index4
with a minimum absolute difference of1
. Therefore, the final return value (the minimized absolute difference) is1
.
In this example, the closest index to start
with the target value 3
was at index 4
, which gave us the minimized absolute difference. This exemplifies the linear scan and comparison process, which results in O(n)
time complexity and O(1)
space complexity since no additional storage beyond a few variables is used.
Solution Implementation
1from typing import List
2
3class Solution:
4 def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
5 # Initialize answer with a large number (infinity)
6 min_distance = float('inf')
7
8 # Iterate through the list, enumerating it to have index and value
9 for index, value in enumerate(nums):
10 # Check if the current value matches the target value
11 if value == target:
12 # Update min_distance with the smaller value between the current min_distance
13 # and the absolute difference between current index and start index
14 min_distance = min(min_distance, abs(index - start))
15
16 # Return the minimum distance found
17 return min_distance
18
19# Example usage:
20# sol = Solution()
21# result = sol.getMinDistance([1, 2, 3, 4, 5], 5, 3)
22# print(result) # Output will be 1, since the distance between index 3 and the closest 5 is 1.
23
1class Solution {
2 public int getMinDistance(int[] nums, int target, int start) {
3 // Get the length of the input array
4 int arrayLength = nums.length;
5 // Initialize the answer with the maximum possible value
6 int minimumDistance = arrayLength;
7
8 // Iterate through the array to find the elements equal to the target
9 for (int i = 0; i < arrayLength; ++i) {
10 // Check if the current element equals the target
11 if (nums[i] == target) {
12 // Update the minimum distance if the current distance is smaller than the previously computed one
13 minimumDistance = Math.min(minimumDistance, Math.abs(i - start));
14 }
15 }
16 // Return the smallest distance found
17 return minimumDistance;
18 }
19}
20
1#include <vector> // Required for using the vector container
2#include <algorithm> // Required for 'min' function
3#include <cmath> // Required for 'abs' function
4
5class Solution {
6public:
7 // Function to find the minimum distance to the target from the start index
8 int getMinDistance(vector<int>& nums, int target, int start) {
9 int size = nums.size(); // Get the size of the input vector 'nums'
10 int minDistance = size; // Initialize minimum distance with the maximum possible value (size of the vector)
11
12 // Loop through all elements in the nums vector
13 for (int i = 0; i < size; ++i) {
14 // Check if the current element is equal to the target
15 if (nums[i] == target) {
16 // Update the minimum distance found so far
17 minDistance = min(minDistance, abs(i - start));
18 }
19 }
20
21 // Return the minimum distance to the target from the start index
22 return minDistance;
23 }
24};
25
1import * as util from "util"; // TypeScript doesn't natively import min and abs, so we would typically use a utility library or implement our own.
2
3// Function to find the minimum distance to the target from the start index
4function getMinDistance(nums: number[], target: number, start: number): number {
5 const size: number = nums.length; // Get the size of the input array 'nums'
6 let minDistance: number = size; // Initialize minimum distance with the maximum possible value (size of the array)
7
8 // Loop through all elements in the nums array
9 for (let i = 0; i < size; ++i) {
10 // Check if the current element is equal to the target
11 if (nums[i] === target) {
12 // Update the minimum distance found so far using Math.min and Math.abs for minimum and absolute value respectively
13 minDistance = Math.min(minDistance, Math.abs(i - start));
14 }
15 }
16
17 // Return the minimum distance to the target from the start index
18 return minDistance;
19}
20
21// Example usage:
22// Uncomment the line below to test the function with an example input
23// console.log(getMinDistance([1, 2, 3, 4], 3, 2));
24
Time and Space Complexity
The time complexity of the given code is O(n)
, where n
is the length of the nums
list. This is because the code iterates through each element of nums
once to check if it is equal to target
and, if so, calculates the distance from the start
index. The min
function, called for each element of the list, operates in constant time O(1)
; hence, it does not affect the overall linear complexity.
The space complexity of the code is O(1)
. This is because the space used does not grow with the size of the input list. The ans
variable takes constant space, and there are no additional data structures used that scale with the input size.
Learn more about how to find time and space complexity quickly using problem constraints.
Which two pointer techniques do you use to check if a string is a palindrome?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!