gpt-4o-mini-2024-07-18· openai
from WildChat-4.8M
give top 5 dsa most importatnt question for interview in python
- Assistant
Hello! How can I assist you today?
- User
give top 5 dsa most importatnt question for interview in python
- Assistant
Hello! How can I assist you today?
give top 5 dsa most importatnt question for interview in python
Certainly! Here are five important data structures and algorithms (DSA) questions that are frequently asked in interviews, along with brief problem descriptions and tips for solving them in Python:
Two Sum Problem
nums and an integer target, return the indices of the two numbers such that they add up to target.nums = [2, 7, 11, 15], target = 9 → Output: [0, 1] (because nums[0] + nums[1] = 9)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
Reverse a Linked List
1 -> 2 -> 3 -> 4 -> 5 → Output: 5 -> 4 -> 3 -> 2 -> 1class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_linked_list(head):
prev = None
curr = head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
Valid Parentheses
(, ), {, }, [ and ], determine if the input string is valid (i.e., every opening bracket has a corresponding closing bracket in the correct order)."{[]}" → Output: Truedef is_valid(s):
stack = []
bracket_map = {')': '(', '}': '{', ']': '['}
for char in s:
if char in bracket_map:
top_element = stack.pop() if stack else '#'
if bracket_map[char] != top_element:
return False
else:
stack.append(char)
return not stack
Merge Intervals
[[1,3],[2,6],[8,10],[15,18]] → Output: [[1,6],[8,10],[15,18]]def merge(intervals):
if not intervals:
return []
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for current in intervals[1:]:
last_merged = merged[-1]
if current[0] <= last_merged[1]: # Overlap
last_merged[1] = max(last_merged[1], current[1])
else:
merged.append(current)
return merged
Find First and Last Position of Element in Sorted Array
nums sorted in non-decreasing order, find the starting and ending position of a given target value.nums = [5,7,7,8,8,10], target = 8 → Output: [3, 4]def search_range(nums, target):
def find_left_index(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
def find_right_index(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] <= target:
left = mid + 1
else:
right = mid - 1
return right
start, end = find_left_index(nums, target), find_right_index(nums, target)
if start <= end:
return [start, end]
else:
return [-1, -1]
These questions effectively test your understanding of basic data structures, algorithms, and problem-solving abilities, so practicing them in Python is beneficial for interviews!