The Most Commonly Asked Questions from Core DSA Topics

Below are the top 10 questions across the essential DSA topics. These problems are frequently asked in coding interviews and cover various difficulty levels. We’ll include problem descriptions, solutions, and code examples for each.

Arrays

  1. Two Sum
    Find two numbers in an array that add up to a target value.
    Solution: Use a hash map for O(n) time complexity.
def two_sum(nums, target):
    hash_map = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hash_map:
            return [hash_map[complement], i]
        hash_map[num] = i

Maximum Subarray (Kadane’s Algorithm)
Find the contiguous subarray with the maximum sum.
Solution: Dynamic programming.

def max_subarray(nums):
    max_sum, curr_sum = nums[0], 0
    for num in nums:
        curr_sum = max(num, curr_sum + num)
        max_sum = max(max_sum, curr_sum)
    return max_sum

Find Duplicate in Array
Use slow-fast pointers or modify the array.

def find_duplicate(nums):
    slow, fast = nums[0], nums[0]
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    fast = nums[0]
    while fast != slow:
        slow = nums[slow]
        fast = nums[fast]
    return slow

Rotate Array
Rotate the array k steps to the right.

def rotate(nums, k):
    k %= len(nums)
    nums[:] = nums[-k:] + nums[:-k]

Merge Intervals

Problem:
Given an array of intervals [[start1, end1], [start2, end2], ...], merge overlapping intervals.

Approach:

  1. Sort intervals by the start value.

  2. Compare the current interval with the last merged interval:

  • If they overlap, merge them by updating the end of the last merged interval.

  • Otherwise, add the current interval to the result.

Code:

def merge_intervals(intervals):
    intervals.sort(key=lambda x: x[0])
    merged = []


for interval in intervals:
        if not merged or merged[-1][1] < interval[0]:
            merged.append(interval)
        else:
            merged[-1][1] = max(merged[-1][1], interval[1])
    return merged
# Example
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
print(merge_intervals(intervals))  # Output: [[1, 6], [8, 10], [15, 18]]

Best Time to Buy and Sell Stock

Problem:
Given prices of a stock for n days, find the maximum profit you can achieve by buying and selling once.

Approach:

  1. Track the minimum price seen so far.

  2. Calculate the profit if sold on the current day.

  3. Update the maximum profit.

Code:

def max_profit(prices):
    min_price = float('inf')
    max_profit = 0

for price in prices:
        min_price = min(min_price, price)
        max_profit = max(max_profit, price - min_price)
    return max_profit
# Example
prices = [7, 1, 5, 3, 6, 4]
print(max_profit(prices))  # Output: 5

Subarray Sum Equals K

Problem:
Find the number of contiguous subarrays that sum to k.

Approach:
Use a hash map to store cumulative sums and their counts. For each element:

  1. Calculate the current cumulative sum.

  2. Check if (cumulative_sum - k) exists in the hash map.

  3. Add the count to the result.

Code:

def subarray_sum(nums, k):
    count = 0
    cumulative_sum = 0
    sum_map = {0: 1}

for num in nums:
        cumulative_sum += num
        count += sum_map.get(cumulative_sum - k, 0)
        sum_map[cumulative_sum] = sum_map.get(cumulative_sum, 0) + 1
    return count
# Example
nums = [1, 1, 1]
k = 2
print(subarray_sum(nums, k))  # Output: 2

Product of Array Except Self

Problem:
For an array nums, return an array where each element at index i is the product of all elements except nums[i], without using division.

Approach:

  1. Compute the prefix product for each element.

  2. Compute the suffix product for each element.

  3. Combine prefix and suffix to get the result.

Code:

def product_except_self(nums):
    n = len(nums)
    res = [1] * n


prefix = 1
    for i in range(n):
        res[i] = prefix
        prefix *= nums[i]
    suffix = 1
    for i in range(n - 1, -1, -1):
        res[i] *= suffix
        suffix *= nums[i]
    return res
# Example
nums = [1, 2, 3, 4]
print(product_except_self(nums))  # Output: [24, 12, 8, 6]

Longest Consecutive Sequence

Problem:
Find the length of the longest consecutive sequence of integers in an array.

Approach:

  1. Use a set for constant-time lookups.

  2. For each number, start counting if it’s the start of a sequence.

  3. Continue counting until the sequence ends.

Code:

def longest_consecutive(nums):
    num_set = set(nums)
    longest = 0

for num in nums:
        if num - 1 not in num_set:
            current_num = num
            current_streak = 1
            while current_num + 1 in num_set:
                current_num += 1
                current_streak += 1
            longest = max(longest, current_streak)
    return longest
# Example
nums = [100, 4, 200, 1, 3, 2]
print(longest_consecutive(nums))  # Output: 4

Triplet Sum (3Sum)

Problem:
Find all unique triplets in the array that sum to zero.

Approach:

  1. Sort the array.

  2. Use a two-pointer approach for each element to find pairs that sum to the target -nums[i].

Code:

def three_sum(nums):
    nums.sort()
    result = []


for i in range(len(nums)):
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        target = -nums[i]
        left, right = i + 1, len(nums) - 1
        while left < right:
            current_sum = nums[left] + nums[right]
            if current_sum == target:
                result.append([nums[i], nums[left], nums[right]])
                left += 1
                right -= 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1
                while left < right and nums[right] == nums[right + 1]:
                    right -= 1
            elif current_sum < target:
                left += 1
            else:
                right -= 1
    return result
# Example
nums = [-1, 0, 1, 2, -1, -4]
print(three_sum(nums))  # Output: [[-1, -1, 2], [-1, 0, 1]]

Reverse Linked List

Problem:
Given the head of a singly linked list, reverse the list and return its head.

Approach:
Use three pointers: prev, curr, and next. Traverse the list, reversing the next pointer of each node.

Code:

class 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

# Example
head = ListNode(1, ListNode(2, ListNode(3)))
new_head = reverse_linked_list(head)
while new_head:
    print(new_head.val, end=" -> ")
    new_head = new_head.next  # Output: 3 -> 2 -> 1

Detect Cycle in Linked List

Problem:
Given a linked list, determine if it has a cycle.

Approach:
Use Floyd’s Tortoise and Hare algorithm with two pointers, slow and fast. If they meet, a cycle is detected.

Code:

def has_cycle(head):
    slow, fast = head, head

    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False

# Example
head = ListNode(1, ListNode(2, ListNode(3)))
head.next.next.next = head.next  # Cycle
print(has_cycle(head))  # Output: True

Merge Two Sorted Lists

Problem:
Merge two sorted linked lists and return it as a new sorted list.

Approach:
Use a dummy node and iterate through both lists, choosing the smaller element each time.

Code:

def merge_two_sorted_lists(l1, l2):
    dummy = ListNode()
    tail = dummy

    while l1 and l2:
        if l1.val < l2.val:
            tail.next = l1
            l1 = l1.next
        else:
            tail.next = l2
            l2 = l2.next
        tail = tail.next

    if l1:
        tail.next = l1
    else:
        tail.next = l2

    return dummy.next

# Example
l1 = ListNode(1, ListNode(2, ListNode(4)))
l2 = ListNode(1, ListNode(3, ListNode(4)))
merged_head = merge_two_sorted_lists(l1, l2)
while merged_head:
    print(merged_head.val, end=" -> ")
    merged_head = merged_head.next  # Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4

Remove Nth Node from End

Problem:
Remove the nth node from the end of a linked list.

Approach:
Use two pointers. Move the first pointer n steps ahead, then move both pointers until the first pointer reaches the end.

Code:

def remove_nth_from_end(head, n):
    dummy = ListNode(0)
    dummy.next = head
    fast = slow = dummy

    for _ in range(n + 1):
        fast = fast.next

    while fast:
        fast = fast.next
        slow = slow.next

    slow.next = slow.next.next
    return dummy.next

# Example
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
new_head = remove_nth_from_end(head, 2)
while new_head:
    print(new_head.val, end=" -> ")  # Output: 1 -> 2 -> 3
    new_head = new_head.next

Intersection of Two Linked Lists

Problem:
Given two linked lists, find the node where they intersect.

Approach:
Calculate the lengths of both lists and align them. Then, traverse both lists simultaneously to find the intersection.

Code:

def get_intersection_node(headA, headB):
    lenA, lenB = 0, 0
    a, b = headA, headB

    while a:
        lenA += 1
        a = a.next
    while b:
        lenB += 1
        b = b.next

    a, b = headA, headB
    if lenA > lenB:
        for _ in range(lenA - lenB):
            a = a.next
    else:
        for _ in range(lenB - lenA):
            b = b.next

    while a and b:
        if a == b:
            return a
        a, b = a.next, b.next

    return None

# Example
headA = ListNode(1, ListNode(2, ListNode(3)))
headB = ListNode(4, ListNode(5, ListNode(6, headA.next)))
print(get_intersection_node(headA, headB).val)  # Output: 2

Copy List with Random Pointers

Problem:
Given a linked list where each node has an additional random pointer, create a deep copy of the list.

Approach:

  1. Copy each node and insert it after the original node.

  2. Set the random pointer of each copied node.

  3. Separate the copied list from the original list.

Code:

class RandomListNode:
    def __init__(self, val=0, next=None, random=None):
        self.val = val
        self.next = next
        self.random = random


def copy_random_list(head):
    if not head:
        return None

    # Step 1: Insert copied nodes
    curr = head
    while curr:
        copied = RandomListNode(curr.val)
        copied.next = curr.next
        curr.next = copied
        curr = copied.next

    # Step 2: Set the random pointers
    curr = head
    while curr:
        if curr.random:
            curr.next.random = curr.random.next
        curr = curr.next.next

    # Step 3: Separate the lists
    curr = head
    copied_head = head.next
    while curr:
        copied = curr.next
        curr.next = copied.next
        if copied.next:
            copied.next = copied.next.next
        curr = curr.next

    return copied_head
# Example
node1 = RandomListNode(1)
node2 = RandomListNode(2)
node1.next = node2
node1.random = node2
node2.random = node1
new_head = copy_random_list(node1)

Palindrome Linked List

Problem:
Check if a linked list is a palindrome.

Approach:

  1. Use the fast-slow pointer technique to find the middle of the list.

  2. Reverse the second half of the list.

  3. Compare the two halves.

Code:

def is_palindrome(head):
    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    prev = None
    while slow:
        next_node = slow.next
        slow.next = prev
        prev = slow
        slow = next_node

    left, right = head, prev
    while right:
        if left.val != right.val:
            return False
        left = left.next
        right = right.next

    return True

# Example
head = ListNode(1, ListNode(2, ListNode(2, ListNode(1))))
print(is_palindrome(head))  # Output: True

Add Two Numbers

Problem:
Add two numbers represented by linked lists.

Approach:
Simulate the addition digit by digit, accounting for carry-over.

Code:

def add_two_numbers(l1, l2):
    dummy = ListNode(0)
    curr = dummy
    carry = 0

    while l1 or l2 or carry:
        val1 = l1.val if l1 else 0
        val2 = l2.val if l2 else 0
        total = val1 + val2 + carry
        carry = total // 10
        curr.next = ListNode(total % 10)
        curr = curr.next
        if l1: l1 = l1.next
        if l2: l2 = l2.next

    return dummy.next

# Example
l1 = ListNode(2, ListNode(4, ListNode(3)))
l2 = ListNode(5, ListNode(6, ListNode(4)))
result = add_two_numbers(l1, l2)
while result:
    print(result.val, end=" -> ")  # Output: 7 -> 0 -> 8
    result = result.next

Flatten a Multilevel Linked List

Problem:
Flatten a linked list where each node has a next pointer and a child pointer.

Approach:
Recursively flatten each level of the list.

Code:

class ListNode:
    def __init__(self, val=0, next=None, child=None):
        self.val = val
        self.next = next
        self.child = child

def flatten(head):
    if not head:
        return None

    curr = head
    while curr:
        if curr.child:
            child = flatten(curr.child)
            temp = curr.next
            curr.next = child
            child_end = child
            while child_end.next:
                child_end = child_end.next
            child_end.next = temp
            curr.child = None
        curr = curr.next

    return head
# Example
head = ListNode(1, ListNode(2, ListNode(3)))
head.next.child = ListNode(7, ListNode(8, ListNode(9)))
flattened = flatten(head)

Sort Linked List

Problem:
Sort a linked list using merge sort.

Approach:
Use merge sort to split the list and then merge the sorted halves.

Code:

def sort_linked_list(head):
    if not head or not head.next:
        return head

# Split the list into two halves
    def split_list(head):
        slow, fast = head, head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return head, slow
    def merge_sorted_lists(l1, l2):
        dummy = ListNode()
        tail = dummy
        while l1 and l2:
            if l1.val < l2.val:
                tail.next = l1
                l1 = l1.next
            else:
                tail.next = l2
                l2 = l2.next
            tail = tail.next
        if l1: tail.next = l1
        if l2: tail.next = l2
        return dummy.next

    left, right = split_list(head)
    left = sort_linked_list(left)
    right = sort_linked_list(right)
    return merge_sorted_lists(left, right)
# Example
head = ListNode(4, ListNode(2, ListNode(1, ListNode(3))))
sorted_head = sort_linked_list(head)
while sorted_head:
    print(sorted_head.val, end=" -> ")  # Output: 1 -> 2 -> 3 -> 4
    sorted_head = sorted_head.next

Valid Palindrome

Question: Write a function to determine if a given string is a palindrome, considering only alphanumeric characters and ignoring cases.

Code:

def is_palindrome(s: str) -> bool:
    filtered = ''.join(char.lower() for char in s if char.isalnum())
    return filtered == filtered[::-1]

# Example usage:
print(is_palindrome("A man, a plan, a canal: Panama"))  # Output: True
print(is_palindrome("race a car"))  # Output: False

Longest Palindromic Substring

Question: Find the longest palindromic substring in a given string.

Code:

def longest_palindromic_substring(s: str) -> str:
    def expand_around_center(left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return s[left+1:right]

    longest = ""
    for i in range(len(s)):
        odd_palindrome = expand_around_center(i, i)
        even_palindrome = expand_around_center(i, i+1)
        longest = max(longest, odd_palindrome, even_palindrome, key=len)
    return longest

# Example usage:
print(longest_palindromic_substring("babad"))  # Output: "bab" or "aba"

Anagram Detection

Question: Check if two strings are anagrams of each other.

Code:

def are_anagrams(s1: str, s2: str) -> bool:
    return sorted(s1) == sorted(s2)

# Example usage:
print(are_anagrams("listen", "silent"))  # Output: True
print(are_anagrams("hello", "world"))    # Output: False

Longest Common Prefix

Question: Write a function to find the longest common prefix string amongst an array of strings.

Code:

def longest_common_prefix(strs: list[str]) -> str:
    if not strs:
        return ""
    prefix = strs[0]
    for s in strs[1:]:
        while not s.startswith(prefix):
            prefix = prefix[:-1]
            if not prefix:
                return ""
    return prefix

# Example usage:
print(longest_common_prefix(["flower", "flow", "flight"]))  # Output: "fl"

Group Anagrams

Question: Group a list of strings into anagrams.

Code:

from collections import defaultdict

def group_anagrams(strs: list[str]) -> list[list[str]]:
    anagrams = defaultdict(list)
    for s in strs:
        sorted_str = ''.join(sorted(s))
        anagrams[sorted_str].append(s)
    return list(anagrams.values())

# Example usage:
print(group_anagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
# Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]

Check if Strings are Rotations

Question: Check if one string is a rotation of another.

Code:

def is_rotation(s1: str, s2: str) -> bool:
    return len(s1) == len(s2) and s2 in s1 + s1

# Example usage:
print(is_rotation("abcde", "cdeab"))  # Output: True
print(is_rotation("abcde", "abced"))  # Output: False

String Compression

Question: Compress a string using the counts of repeated characters.

Code:

def compress_string(s: str) -> str:
    compressed = []
    count = 1
    for i in range(1, len(s)):
        if s[i] == s[i-1]:
            count += 1
        else:
            compressed.append(s[i-1] + str(count))
            count = 1
    compressed.append(s[-1] + str(count))
    return ''.join(compressed) if len(compressed) < len(s) else s

# Example usage:
print(compress_string("aabcccccaaa"))  # Output: "a2b1c5a3"

Count and Say

Question: Implement the “count and say” sequence.

Code:

def count_and_say(n: int) -> str:
    if n == 1:
        return "1"
    prev = count_and_say(n-1)
    result, count = "", 1
    for i in range(1, len(prev)):
        if prev[i] == prev[i-1]:
            count += 1
        else:
            result += str(count) + prev[i-1]
            count = 1
    result += str(count) + prev[-1]
    return result

# Example usage:
print(count_and_say(4))  # Output: "1211"

Reverse Words in a String

Question: Reverse the words in a given string.

Code:

def reverse_words(s: str) -> str:
    return ' '.join(reversed(s.split()))

# Example usage:
print(reverse_words("the sky is blue"))  # Output: "blue is sky the"

Minimum Window Substring

Question: Find the minimum window substring that contains all the characters of a given string.

Code:

from collections import Counter


def min_window(s: str, t: str) -> str:
    if not t or not s:
        return ""
    target_count = Counter(t)
    current_count = Counter()
    left, right, start, min_len = 0, 0, 0, float("inf")
    required = len(target_count)
    formed = 0
    while right < len(s):
        current_count[s[right]] += 1
        if s[right] in target_count and current_count[s[right]] == target_count[s[right]]:
            formed += 1
        while left <= right and formed == required:
            if (right - left + 1) < min_len:
                start, min_len = left, right - left + 1
            current_count[s[left]] -= 1
            if s[left] in target_count and current_count[s[left]] < target_count[s[left]]:
                formed -= 1
            left += 1
        right += 1
    return s[start:start + min_len] if min_len != float("inf") else ""
# Example usage:
print(min_window("ADOBECODEBANC", "ABC"))  # Output: "BANC"

Valid Parentheses

Question: Write a function to check if a string containing just the characters (, ), {, }, [, and ] is valid (correctly matched).

Code:

def is_valid_parentheses(s: str) -> bool:
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}
    for char in s:
        if char in mapping:
            top_element = stack.pop() if stack else '#'
            if mapping[char] != top_element:
                return False
        else:
            stack.append(char)
    return not stack

# Example usage:
print(is_valid_parentheses("()[]{}"))  # Output: True
print(is_valid_parentheses("(]"))      # Output: False

Min Stack

Question: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Code:

class MinStack:
    def __init__(self):
        self.stack = []
        self.min_stack = []

def push(self, val: int):
        self.stack.append(val)
        if not self.min_stack or val <= self.min_stack[-1]:
            self.min_stack.append(val)
    def pop(self):
        if self.stack.pop() == self.min_stack[-1]:
            self.min_stack.pop()
    def top(self) -> int:
        return self.stack[-1]
    def get_min(self) -> int:
        return self.min_stack[-1]
# Example usage:
min_stack = MinStack()
min_stack.push(-2)
min_stack.push(0)
min_stack.push(-3)
print(min_stack.get_min())  # Output: -3
min_stack.pop()
print(min_stack.top())      # Output: 0
print(min_stack.get_min())  # Output: -2

Evaluate Reverse Polish Notation

Question: Evaluate the value of an arithmetic expression in Reverse Polish Notation (RPN).

Code:

def eval_rpn(tokens: list[str]) -> int:
    stack = []
    for token in tokens:
        if token in "+-*/":
            b, a = stack.pop(), stack.pop()
            if token == '+':
                stack.append(a + b)
            elif token == '-':
                stack.append(a - b)
            elif token == '*':
                stack.append(a * b)
            elif token == '/':
                stack.append(int(a / b))
        else:
            stack.append(int(token))
    return stack[0]

# Example usage:
print(eval_rpn(["2", "1", "+", "3", "*"]))  # Output: 9

Daily Temperatures

Question: Given a list of temperatures, find how many days you would have to wait until a warmer temperature.

Code:

def daily_temperatures(temperatures: list[int]) -> list[int]:
    result = [0] * len(temperatures)
    stack = []
    for i, temp in enumerate(temperatures):
        while stack and temp > temperatures[stack[-1]]:
            prev_index = stack.pop()
            result[prev_index] = i - prev_index
        stack.append(i)
    return result

# Example usage:
print(daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73]))
# Output: [1, 1, 4, 2, 1, 1, 0, 0]

Next Greater Element

Question: Find the next greater element for each element in a list.

Code:

def next_greater_element(nums: list[int]) -> list[int]:
    result = [-1] * len(nums)
    stack = []
    for i in range(len(nums)):
        while stack and nums[i] > nums[stack[-1]]:
            result[stack.pop()] = nums[i]
        stack.append(i)
    return result

# Example usage:
print(next_greater_element([4, 5, 2, 25]))  # Output: [5, 25, 25, -1]

Sliding Window Maximum

Question: Find the maximum value in each sliding window of size k.

Code:

from collections import deque

def max_sliding_window(nums: list[int], k: int) -> list[int]:
    dq = deque()
    result = []
    for i, num in enumerate(nums):
        if dq and dq[0] == i - k:
            dq.popleft()
        while dq and nums[dq[-1]] < num:
            dq.pop()
        dq.append(i)
        if i >= k - 1:
            result.append(nums[dq[0]])
    return result
# Example usage:
print(max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3))
# Output: [3, 3, 5, 5, 6, 7]

Implement Queue Using Stacks

Question: Implement a queue using two stacks.

Code:

class MyQueue:
    def __init__(self):
        self.stack1 = []
        self.stack2 = []

def push(self, x: int):
        self.stack1.append(x)
    def pop(self) -> int:
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()
    def peek(self) -> int:
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]
    def empty(self) -> bool:
        return not self.stack1 and not self.stack2
# Example usage:
queue = MyQueue()
queue.push(1)
queue.push(2)
print(queue.peek())  # Output: 1
print(queue.pop())   # Output: 1
print(queue.empty()) # Output: False

Decode String

Question: Decode a string encoded with pattern k[encoded_string].

Code:

def decode_string(s: str) -> str:
    stack = []
    current_num = 0
    current_string = ""
    for char in s:
        if char.isdigit():
            current_num = current_num * 10 + int(char)
        elif char == '[':
            stack.append((current_string, current_num))
            current_string, current_num = "", 0
        elif char == ']':
            prev_string, num = stack.pop()
            current_string = prev_string + current_string * num
        else:
            current_string += char
    return current_string

# Example usage:
print(decode_string("3[a2[c]]"))  # Output: "accaccacc"

Trapping Rain Water

Question: Calculate the amount of rainwater trapped between buildings.

Code:

def trap(height: list[int]) -> int:
    left, right = 0, len(height) - 1
    left_max, right_max = 0, 0
    water = 0
    while left < right:
        if height[left] < height[right]:
            if height[left] >= left_max:
                left_max = height[left]
            else:
                water += left_max - height[left]
            left += 1
        else:
            if height[right] >= right_max:
                right_max = height[right]
            else:
                water += right_max - height[right]
            right -= 1
    return water

# Example usage:
print(trap([0,1,0,2,1,0,1,3,2,1,2,1]))  # Output: 6

Simplify Path

Question: Simplify a Unix-style absolute file path.

Code:

def simplify_path(path: str) -> str:
    stack = []
    for part in path.split("/"):
        if part == "..":
            if stack:
                stack.pop()
        elif part and part != ".":
            stack.append(part)
    return "/" + "/".join(stack)

# Example usage:
print(simplify_path("/home/../usr//bin/"))  # Output: "/usr/bin"