Python - Check if Kth index elements are unique
Last Updated :
26 Apr, 2023
Given a String list, check if all Kth index elements are unique.
Input : test_list = ["gfg", "best", "for", "geeks"], K = 1
Output : False
Explanation : e occurs as 1st index in both best and geeks.
Input : test_list = ["gfg", "best", "geeks"], K = 2
Output : True
Explanation : g, s, e, all are unique.
Method #1 : Using loop
This is brute way to solve this problem. In this, we iterate for each string and flag off when any element is repeated, and return false.
Python3
# Python3 code to demonstrate working of
# Check if Kth index elements are unique
# Using loop
# initializing list
test_list = ["gfg", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
res = []
flag = True
for ele in test_list:
# checking if element is repeated
if ele[K] in res:
flag = False
break
else:
res.append(ele[K])
# printing result
print("Is Kth index all unique : " + str(flag))
OutputThe original list is : ['gfg', 'best', 'for', 'geeks']
Is Kth index all unique : True
Method #2 : Using Counter() + all()
In this, we count frequency of each char. at Kth index, and all() is used to check if Counter is less than 2 for all.
Python3
# Python3 code to demonstrate working of
# Check if Kth index elements are unique
# Using Counter() + all()
from collections import Counter
# initializing list
test_list = ["gfg", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# getting count of each Kth index item
count = Counter(sub[K] for sub in test_list)
# extracting result
res = all(val < 2 for val in count.values())
# printing result
print("Is Kth index all unique : " + str(res))
OutputThe original list is : ['gfg', 'best', 'for', 'geeks']
Is Kth index all unique : True
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using list(),set() methods
Python3
# Python3 code to demonstrate working of
# Check if Kth index elements are unique
# initializing list
test_list = ["gfg", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
res = False
if(test_list[K] != list(set(test_list[K]))):
res = True
# printing result
print("Is Kth index all unique : " + str(res))
OutputThe original list is : ['gfg', 'best', 'for', 'geeks']
Is Kth index all unique : True
Method #4: Using list comprehension and set()
Algorithm:
- Initialize an empty set and an empty list to keep track of unique elements.
- Traverse through the given list and extract the Kth index element of each string.
- Check if the element is already present in the set.
- If it is already present, return False as it means there is a duplicate.
- If not, add the element to the set and the list.
- After traversing the whole list, compare the length of the set and the list.
- If they are equal, it means all elements were unique. Return True.
- If not, it means there was at least one duplicate. Return False.
Python3
#Python3 code to demonstrate working of
#Check if Kth index elements are unique
#Using set
#initializing list
test_list = ["gfg", "best", "for", "geeks"]
#printing original list
print("The original list is : " + str(test_list))
#initializing K
K = 2
#Using set to check unique Kth index elements
unique = len(set([ele[K] for ele in test_list])) == len([ele[K] for ele in test_list])
#printing result
print("Is Kth index all unique : " + str(unique))
#This code is contributed by Vinay Pinjala.
OutputThe original list is : ['gfg', 'best', 'for', 'geeks']
Is Kth index all unique : True
Time Complexity: O(n), where n is the number of strings in the list. We need to traverse through the entire list only once.
Space Complexity: O(n), where n is the number of strings in the list. In the worst case, all Kth index elements are unique, so the set and the list will contain n elements.
Method 5 : using dictionary.
steps to implement this method:
Initialize an empty dictionary to keep track of the frequency of each element at the Kth index.
Loop through the elements in the input list and check if the element at the Kth index is already in the dictionary.
If the element is already in the dictionary, increment its frequency by 1.
If the element is not in the dictionary, add it with frequency 1.
Finally, check if any element in the dictionary has a frequency greater than 1. If so, return False, else return True.
Python3
test_list = ["gfg", "best", "for", "geeks"]
print("The original list is : " + str(test_list))
K = 2
freq_dict = {}
for ele in test_list:
if ele[K] in freq_dict:
freq_dict[ele[K]] += 1
else:
freq_dict[ele[K]] = 1
unique = all(value == 1 for value in freq_dict.values())
print("Is Kth index all unique : " + str(unique))
OutputThe original list is : ['gfg', 'best', 'for', 'geeks']
Is Kth index all unique : True
The time complexity of this approach is O(N), where N is the length of the input list.
The auxiliary space required by this approach is O(K), where K is the number of unique elements at the Kth index.
Similar Reads
Python - Check if all elements in List are same
To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. Pythona = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) OutputTrue Explanation:Converting
3 min read
Python - First K unique elements
Sometimes, while working with Python Lists, we can have a problem in which we need to extract first K unique elements. This means we need to extract duplicate if they occur in first K elements as well. This can essentially make count of first K unique elements more than K. This kind of problem can h
3 min read
Python - Check if elements index are equal for list elements
Given two lists and check list, test if for each element in check list, elements occur in similar index in 2 lists. Input : test_list1 = [2, 6, 9, 7, 8], test_list2 = [2, 7, 9, 4, 8], check_list = [9, 8, 7] Output : False Explanation : 7 is at 4th and 2nd place in both list, hence False. Input : tes
4 min read
Python - Check if element is present in tuple
We are given a tuple and our task is to find whether given element is present in tuple or not. For example x = (1, 2, 3, 4, 5) and we need to find if 3 is present in tuple so that in this case resultant output should be True.Using in Operatorin operator checks if an element is present in a tuple by
2 min read
Python | Check if all elements in a list are identical
Given a list, write a Python program to check if all the elements in that list are identical using Python. Examples: Input : ['a', 'b', 'c'] Output : False Input : [1, 1, 1, 1] Output : TrueCheck if all elements in a list are identical or not using a loop Start a Python for loop and check if the f
5 min read
Python - Test if all elements are unique in columns in a Matrix
Given a Matrix, test if all columns contain unique elements. Input : test_list = [[3, 4, 5], [1, 2, 4], [4, 1, 10]] Output : True Explanation : 3, 1, 4; 4, 2, 1; 5, 4, 10; All elements are unique in columns. Input : test_list = [[3, 4, 5], [3, 2, 4], [4, 1, 10]] Output : False Explanation : 3, 3, 4;
5 min read
Python - Group Tuples by Kth Index Element
Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of elements of tuple by similar Kth index element. This kind of problem can have application in web development domain. Let's discuss the certain way in which this task can be performed. Input :
5 min read
Python - Closest Pair to Kth index element in Tuple
In the given problem, condition K specifies the maximum allowable difference between corresponding elements of tuples, i.e., it represents the proximity threshold for finding the nearest tuple. The goal is to find the tuple in the list whose elements have the smallest maximum difference compared to
7 min read
Python - Check if any list element is present in Tuple
Given a tuple, check if any list element is present in it. Input : test_tup = (4, 5, 10, 9, 3), check_list = [6, 7, 10, 11] Output : True Explanation : 10 occurs in both tuple and list. Input : test_tup = (4, 5, 12, 9, 3), check_list = [6, 7, 10, 11] Output : False Explanation : No common elements.
6 min read
Python - Index Directory of Elements
Given a list of elements, the task is to write a python program to compute all the indices of all the elements. Examples: Input: test_list = [7, 6, 3, 7, 8, 3, 6, 7, 8] Output: {8: [4, 8], 3: [2, 5], 6: [1, 6], 7: [0, 3, 7]} Explanation: 8 occurs at 4th and 8th index, 3 occurs at 2nd and 5th index a
3 min read