Python – Rear Kth elements
Given a list, the task is to extract all Kth elements from rear end.
Input : test_list = [3, 4, 5, 2, 1], K = 2 Output : [1, 5, 3] Explanation : Every 2nd elements are extracted from rear starting from 1. Input : test_list = [3, 4, 5], K = 1 Output : [5, 4, 3] Explanation : Every elements are extracted from rear starting from 1.
Method #1 : Using loop The is brute method to solve this problem. In this, we reverse and then perform iteration to get each Kth multiple element.
Python3
test_list = [ 3 , 5 , 7 , 9 , 10 , 2 , 8 , 6 ]
print ("The original list is : " + str (test_list))
K = 3
res = []
test_list.reverse()
for idx, ele in enumerate (test_list):
if idx % K = = 0 :
res.append(ele)
print ("Rear Kth elements : " + str (res))
|
Output :
The original list is : [3, 5, 7, 9, 10, 2, 8, 6]
Rear Kth elements : [6, 10, 5]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. loop performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #2 : Using list slicing This is shorthand version solution to this problem. We use power of list slicing skip to skip Kth element, and also reverse it.
Python3
test_list = [ 3 , 5 , 7 , 9 , 10 , 2 , 8 , 6 ]
print ("The original list is : " + str (test_list))
K = 3
res = test_list[ - 1 :: - K]
print ("Rear Kth elements : " + str (res))
|
Output :
The original list is : [3, 5, 7, 9, 10, 2, 8, 6]
Rear Kth elements : [6, 10, 5]
Method #3 : Using while loop+abs()
Approach
This approach extracts every kth element from the rear of the input list by iterating over the list with a while loop and using negative indexing.
Algorithm
1. Initialize an empty result list.
2. Start a loop with index i = -1, which starts from the last element of the list.
3. While the absolute value of i is less than or equal to the length of the list:
a. Append the element at index i to the result list.
b. Decrement the index i by k.
4. Return the result list.
Python3
def rear_kth_elements(test_list, k):
result = []
i = - 1
while abs (i) < = len (test_list):
result.append(test_list[i])
i - = k
return result
test_list = [ 3 , 4 , 5 , 2 , 1 ]
k = 2
result = rear_kth_elements(test_list, k)
print (result)
|
Time complexity: O(n/k), where n is the length of the input list. This is because we iterate over every kth element in the list and append it to the result list. Therefore, the number of iterations is proportional to n/k.
Auxiliary Space: O(n/k), where n is the length of the input list. This is because we store every kth element of the list in the result list, which has a length of n/k. Therefore, the space required is proportional to n/k.
Last Updated :
14 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...