Python – Nearest occurrence between two elements in a List
Last Updated :
01 May, 2023
Given a list and two elements, x and y find the nearest occurrence index of element x from element y.
Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 4, y = 6
Output : 1
Explanation : 4 is found at 1, 12 and 14th index, 6 is at 5th index, nearest is 1st index.
Input : test_list = [2, 4, 5, 7, 8, 6, 3, 8, 7, 2, 0, 9, 4, 9, 4], x = 7, y = 6
Output : 3
Explanation : 7 is found at 3rd and 8th index, 6 is at 5th index, nearest is 3rd index.
Method : Using list comprehension + loop + index()
In this, we find all indices of y using list comprehension, and then get index of x using index(), post that loop is used to get index difference, and the nearest index is returned as result.
Python3
def nearestOccurrenceIndex(test_list, x, y):
if x not in test_list or y not in test_list:
return - 1
x_idx = [idx for idx in range ( len (test_list)) if test_list[idx] = = x]
y_idx = test_list.index(y)
min_dist = 1000000
res = None
for ele in x_idx:
if abs (ele - y_idx) < min_dist:
res = ele
min_dist = abs (ele - y_idx)
return res
input_list = [ 2 , 4 , 5 , 7 , 8 , 6 , 3 , 8 , 4 , 2 , 0 , 9 , 4 , 9 , 4 ]
print ( "The original list is : " + str (input_list))
x = 4
y = 6
print ( "Minimum distance index: " , nearestOccurrenceIndex(input_list, x, y))
|
Output
The original list is : [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4]
Minimum distance index: 8
Time Complexity: O(n), where n is the length of the list.
Auxiliary Space: O(1)
Method #2: Using linear search
Approach:
We use linear search to find the nearest occurrence of two elements x and y in the input list. The algorithm iterates through the list using a for loop and checks if the current element is equal to x or y. If the current element is equal to x or y, it checks if min_dist is None or if the distance between the current index and min_idx is less than min_dist. If the distance between the current index and min_idx is less than min_dist or min_dist is None, it updates min_dist and min_idx. At the end of the loop, if both x and y are found in the list, the algorithm returns min_dist. Otherwise, it returns -1 to indicate that one of the elements was not found in the list.
Algorithm:
- Initialize variables min_dist and min_idx to be None
- Iterate through the list using a for loop and check if the current element is equal to x or y.
- If the current element is equal to x or y, check if min_dist is None or if the distance between the current index and min_idx is less than min_dist.
- If the distance between the current index and min_idx is less than min_dist or min_dist is None, update min_dist and min_idx.
- If both x and y are found in the list, return min_dist. Otherwise, return -1.
- End.
Python3
def nearest_occurrence_linear(test_list, x, y):
min_dist = None
min_idx = None
for i in range ( len (test_list)):
if test_list[i] = = x or test_list[i] = = y:
if min_idx is not None and test_list[i] ! = test_list[min_idx]:
dist = i - min_idx
if min_dist is None or dist < min_dist:
min_dist = dist
min_idx = i
if min_dist is not None :
return min_dist
else :
return - 1
test_list = [ 2 , 4 , 5 , 7 , 8 , 6 , 3 , 8 , 4 , 2 , 0 , 9 , 4 , 9 , 4 ]
x = 4
y = 6
print (nearest_occurrence_linear(test_list, x, y))
|
Time Complexity: O(n), where n is the length of the list
Space Complexity: O(1)
Method 3: Using 2 pointers
Steps:
- Initialize two pointers, one for x and one for y, to -1.
- Initialize a variable to store the minimum distance to a large value, such as float(‘inf’).
- Loop through the list, and for each element, update the index of the corresponding pointer if it matches x or y.
- If both pointers have been updated, calculate the distance between them and update the minimum distance variable if the distance is smaller than the current minimum.
- Return the index of the pointer that was updated last.
Example:
Python3
def nearestOccurrenceIndex(test_list, x, y):
x_idx = - 1
y_idx = - 1
min_dist = float ( 'inf' )
for i, val in enumerate (test_list):
if val = = x:
x_idx = i
elif val = = y:
y_idx = i
if x_idx ! = - 1 and y_idx ! = - 1 :
dist = abs (x_idx - y_idx)
if dist < min_dist:
min_dist = dist
if x_idx > y_idx:
res = x_idx
else :
res = y_idx
if min_dist = = float ( 'inf' ):
return - 1
return res
input_list = [ 2 , 4 , 5 , 7 , 8 , 6 , 3 , 8 , 4 , 2 , 0 , 9 , 4 , 9 , 4 ]
print ( "The original list is : " + str (input_list))
x = 4
y = 6
print ( "Minimum distance index: " , nearestOccurrenceIndex(input_list, x, y))
|
Output
The original list is : [2, 4, 5, 7, 8, 6, 3, 8, 4, 2, 0, 9, 4, 9, 4]
Minimum distance index: 8
Time complexity: O(n), since we need to loop through the entire list.
Auxiliary space: O(1), since we only need to store a few variables that don’t depend on the size of the input list.
Similar Reads
Last Occurrence of Some Element in a List - Python
We are given a list we need to find last occurrence of some elements in list. For example, w = ["apple", "banana", "orange", "apple", "grape"] we need to find last occurrence of string 'apple' so output will be 3 in this case. Using rindex()rindex() method in Python returns the index of the last occ
3 min read
Python - Distance between occurrences
Sometimes, while working with Python Strings, we can have a task in which we need to find the indices difference between occurrences of a particular character. This can have applications in domains such as day-day programming. Let us discuss certain ways in which this task can be done. Method #1: Us
5 min read
Move One List Element to Another List - Python
The task of moving one list element to another in Python involves locating a specific element in the source list, removing it, and inserting it into the target list at a desired position. For example, if a = [4, 5, 6, 7, 3, 8] and b = [7, 6, 3, 8, 10, 12], moving 10 from b to index 4 in a results in
3 min read
Test if all elements are present in list-Python
The task of testing if all elements are present in a list in Python involves checking whether every item in a target list exists within a reference list. For example, given two lists a = [6, 4, 8, 9, 10] and b = [4, 6, 9], the task is to confirm that all elements in list b are also found in list a.
3 min read
Python - Get the indices of all occurrences of an element in a list
We are given a list and our task is to find all the indices where a particular element occurs. For example, if we have a list like [1, 2, 3, 2, 4, 2] and the element is 2, then the output will be [1, 3, 5] because 2 appears at these positions. Using List ComprehensionList comprehension allows for a
2 min read
Python | Check if any element occurs n times in given list
Given a list, the task is to find whether any element occurs 'n' times in given list of integers. It will basically check for the first element that occurs n number of times. Examples: Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2], n = 3 Output : 2 Input: l = [1, 2, 3, 4, 0, 4, 3, 2, 1, 2, 1, 1], n = 4
5 min read
Python Program to find the Next Nearest element in a Matrix
Given a matrix, a set of coordinates and an element, the task is to write a python program that can get the coordinates of the elements next occurrence. Input : test_list = [[4, 3, 1, 2, 3], [7, 5, 3, 6, 3], [8, 5, 3, 5, 3], [1, 2, 3, 4, 6]], i, j = 1, 3, K = 3 Output : (1, 4) Explanation : After (1
4 min read
Python - Find the distance between first and last even elements in a List
Given a List, write a Python program to find the span of even elements in list, i.e distance between first and last occurrence of even element. Examples: Input : test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11] Output : 5 Explanation : Even elements begin at 4 and end at 10, spanning 5 indices. Input :
5 min read
Python - Extract elements with Range consecutive occurrences
Sometimes while working with data, we can have a problem in which we need to select some of the elements that occur range times consecutively. This problem can occur in many domains. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using groupby() + list comprehension This
4 min read
Python - Substitute K for first occurrence of elements
Sometimes, while working with Python data, we can have a problem in which, we need to perform a substitution to the first occurrence of each element in list. This type of problem can have application in various domains such as web development. Let's discuss certain ways in which this task can be per
6 min read