TCS NQT 2025 Coding Question: Find Second Largest Element (Python Solution)
The TCS NQT 2025 coding round is known for asking array manipulation questions. One of the most repeated questions in the "tcs digital" and "prime" slots is finding the second largest element in an array without using built-in sorting functions.
If you are preparing for the upcoming off-campus drive, here is the logic and Python code to solve this problem efficiently.
Problem Statement: Given an array of integers, find the second largest distinct element.
Input: [12, 35, 1, 10, 34, 1]
Output: 34
Why is this tricky?
Many students make the mistake of simply sorting the array arr.sort() and picking the second last element. However, if the array has duplicates (e.g., [10, 10, 9]), this method fails because the last two elements are the same.
Python Solution (O(N) Approach): Here is the correct Python code that handles duplicates and runs in linear time:
def get_second_largest(arr):
# Remove duplicates to avoid errors
unique_elements = list(set(arr))
# If list has less than 2 elements, no second largest exists
if len(unique_elements) < 2:
return -1
# Sort the unique list
unique_elements.sort()
# Return the second last element
return unique_elements[-2]
# Driver Code
arr = [12, 35, 1, 10, 34, 1]
print("Second Largest is:", get_second_largest(arr))
Interview Tip:
When the interviewer asks you this, explain that using set() removes duplicates, which ensures that even if the input is [10, 10, 10], your code handles it gracefully.
Upcoming Drives Make sure to practice this logic before your exam date. For more Python coding solutions for TCS, Wipro, and Accenture, bookmark this page.
Comments
Post a Comment