Find the Second Largest Number in a List in Python

Find the Second Largest Number in a List in Python Finding the second largest element is a common interview problem. The key challenge is handling duplicates correctly. Solution 1: Remove Duplicates, Then Sort def second_largest(nums): unique = list(set(nums)) unique.sort() return unique[-2] print(second_largest([10, 20, 4, 45, 99, 99])) # Output: 45 Solution 2: Using sorted() and…

Read More

Check for Prime Numbers in Python

Check for Prime Numbers in Python A prime number is a number greater than 1 that has no divisors other than 1 and itself. Efficiently checking for primes is a classic coding problem. Efficient Solution (Check up to Square Root) import math def is_prime(n): if n < 2: return False for i in range(2, int(math.sqrt(n))...

Read More

Check for Palindrome in Python

Check for Palindrome in Python A palindrome is a string that reads the same forwards and backwards, such as “racecar” or “madam”. This problem builds directly on string reversal. Simple Solution def is_palindrome(s): return s == s[::-1] # Examples print(is_palindrome(“racecar”)) # True print(is_palindrome(“hello”)) # False Case-Insensitive Check def is_palindrome_ci(s): s = s.lower().replace(” “, “”) return…

Read More

Reverse a String in Python

Reverse a String in Python One of the most common Python interview questions is reversing a string. Python makes this elegant with slicing. The Pythonic Way def reverse_string(s): return s[::-1] # Example print(reverse_string(“hello”)) # Output: “olleh” How It Works The slicing syntax s[::-1] means: start from the end, go to the beginning, step by -1…

Read More
Verified by MonsterInsights