Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Check if all elements in a list are identical
Next article icon

Python – Check if Kth index elements are unique

Last Updated : 26 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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))
 
 
Output
The 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))
 
 
Output
The 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))
 
 
Output
The original list is : ['gfg', 'best', 'for', 'geeks'] Is Kth index all unique : True

Method #4: Using list comprehension and set()

Algorithm:

  1. Initialize an empty set and an empty list to keep track of unique elements.
  2. Traverse through the given list and extract the Kth index element of each string.
  3. Check if the element is already present in the set.
  4. If it is already present, return False as it means there is a duplicate.
  5. If not, add the element to the set and the list.
  6. After traversing the whole list, compare the length of the set and the list.
  7. If they are equal, it means all elements were unique. Return True.
  8. 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.
 
 
Output
The 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))
 
 
Output
The 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.



Next Article
Python | Check if all elements in a list are identical
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

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. [GFGTABS] Python a = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) [/GFGTABS]OutputTrue Ex
    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 fir
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences