from collections import Counter
def most_frequent_element(lst):
freq = Counter(lst)
most_common = min(freq.items(), key=lambda x: (-x[1], x[0]))
return most_common[0]
# Example usage:
lst = [3, 1, 3, 2, 3, 4, 1, 1, 1]
print(most_frequent_element(lst)) # Output: 1
Counter
from the collections
module to count the frequency of each element.min
to find the most frequent element, with a custom key that prioritizes higher frequency and, in case of a tie, the smallest element.
def is_balanced(s):
stack = []
for char in s:
if char == '(':
stack.append(char)
elif char == ')':
if not stack or stack.pop() != '(':
return False
return len(stack) == 0
# Example usage:
print(is_balanced("(())")) # Output: True
print(is_balanced("(()")) # Output: False
def intersection(arr1, arr2):
return list(set(arr1) & set(arr2))
# Example usage:
arr1 = [1, 2, 2, 1]
arr2 = [2, 2]
print(intersection(arr1, arr2)) # Output: [2]
&
) operator to find common elements.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_linked_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
# Example usage:
# Linked list: 1 -> 2 -> 3
head = ListNode(1, ListNode(2, ListNode(3)))
new_head = reverse_linked_list(head)
prev
, current
, and next_node
to reverse the list in one pass.
def length_of_longest_substring(s):
char_set = set()
left = 0
max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length
# Example usage:
print(length_of_longest_substring("abcabcbb")) # Output: 3
left
and right
) and a set to track characters in the window.left
pointer to the right until the character is removed.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_sorted_lists(l1, l2):
dummy = ListNode()
current = dummy
while l1 and l2:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
# Append remaining nodes
current.next = l1 if l1 else l2
return dummy.next
# Example usage:
# l1: 1 -> 2 -> 4
# l2: 1 -> 3 -> 4
def find_duplicates(nums):
seen = set()
duplicates = []
for num in nums:
if num in seen:
duplicates.append(num)
else:
seen.add(num)
return duplicates
# Example usage:
print(find_duplicates([1, 2, 3, 1, 4, 5, 2])) # Output: [1, 2]
duplicates
when an element is encountered again.
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
# Example usage:
print(two_sum([2, 7, 11, 15], 9)) # Output: [0, 1]
import heapq
def find_kth_largest(nums, k):
return heapq.nlargest(k, nums)[-1]
# Example usage:
print(find_kth_largest([3, 2, 1, 5, 6, 4], 2)) # Output: 5
heapq.nlargest()
to get the K largest elements and return the last element.