Friday, August 29, 2025
HomeLanguagesPython – Non K distant elements

Python – Non K distant elements

Given a list, the task is to write a Python program to extract all the elements such that no element is at K distant from one other.

Examples:

Input : test_list = [8, 10, 16, 20, 3, 1, 7], K = 2 
Output : [16, 20, 7] 
Explanation : 16 + 2 = 18, 16 – 2 = 14, both are not in list, hence filtered.

Input : test_list = [8, 10, 16, 20], K = 2 
Output : [16, 20, 7] 
Explanation : 16 + 2 = 18, 16 – 2 = 14, both are not in list, hence filtered. 

Method #1: Using loop

In this we iterate for all the elements and using in operator check for each element if has element at K distance from it, if found, its not included in list.

Python3




# Python3 code to demonstrate working of
# Non K distant elements
# Using loop
 
# initializing list
test_list = [8, 10, 16, 20, 3, 1, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
res = []
for ele in test_list:
 
    # check for K distant
    if ele + K not in test_list and ele - K not in test_list:
        res.append(ele)
 
# printing result
print("The filtered List : " + str(res))


Output

The original list is : [8, 10, 16, 20, 3, 1, 7]
The filtered List : [16, 20, 7]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using list comprehension

In this, we perform task of filtering and iteration using 1 liner using list comprehension.

Python3




# Python3 code to demonstrate working of
# Non K distant elements
# Using list comprehension
 
# initializing list
test_list = [8, 10, 16, 20, 3, 1, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing K
K = 2
 
# using list comprehension to get all elements of non K distance
res = [ele for ele in test_list if ele +
       K not in test_list and ele - K not in test_list]
 
# printing result
print("The filtered List : " + str(res))


Output

The original list is : [8, 10, 16, 20, 3, 1, 7]
The filtered List : [16, 20, 7]

Time Complexity: O(n)
Auxiliary Space: O(n)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32247 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6615 POSTS0 COMMENTS
Nicole Veronica
11788 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11835 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7011 POSTS0 COMMENTS
Thapelo Manthata
6686 POSTS0 COMMENTS
Umr Jansen
6699 POSTS0 COMMENTS