Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that finds the maximum sum of any contiguous subarray (Kadane's algorithm).

Explanation:
Kadane's algorithm is the standard O(n) solution.
1. I keep track of the current sum and the best sum seen so far.
2. At each element, I decide: extend the current subarray or start fresh.
3. This is: current = max(num, current + num).
4. I update best = max(best, current).
5. This works because a subarray ending at position i is either the element itself or the element plus the best subarray ending at i-1.

Output:
def max_subarray(nums):
    best = nums[0]
    current = nums[0]
    for n in nums[1:]:
        current = max(n, current + n)
        best = max(best, current)
    return best


Input: Write a function to reverse a linked list.

Explanation:
I'll reverse the linked list iteratively.
1. Use three pointers: prev, current, next.
2. For each node, save next, point current.next to prev, then advance.
3. At the end, prev will be the new head.
4. This is O(n) time and O(1) space.

Output:
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

# Using dict as node for testing
n3 = {'val': 3, 'next': None}
n2 = {'val': 2, 'next': n3}
n1 = {'val': 1, 'next': n2}
reversed_head = reverse_linked_list(n1)
assert reversed_head['val'] == 3
assert reversed_head['next']['val'] == 2
assert reversed_head['next']['next']['val'] == 1


Input: Write a function that reverses a string in-place.

Explanation:
Let me think about reversing a string.
1. To reverse in-place, I need two pointers: one at start, one at end.
2. I swap characters at both pointers, then move them inward.
3. I continue until the pointers meet or cross.
4. For Python strings (immutable), I'll convert to a list first.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that merges overlapping intervals.

Explanation:
Let me solve interval merging.
1. First, sort intervals by start time.
2. Then iterate through sorted intervals.
3. If the current interval overlaps with the last merged interval, merge them.
4. Overlap condition: current.start <= last_merged.end.
5. Merged end = max(last_merged.end, current.end).
6. If no overlap, add current to result.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that performs binary search on a sorted list.

Explanation:
Binary search is O(log n) on sorted arrays.
1. Set left = 0, right = len(arr) - 1.
2. While left <= right, check the middle element.
3. If middle == target, return its index.
4. If middle < target, search right half.
5. If middle > target, search left half.
6. If not found, return -1.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input: Write a function that checks if two strings are anagrams.

Explanation:
Two strings are anagrams if they have the same characters with the same frequencies.
1. First approach: sort both strings and compare O(n log n).
2. Better approach: count character frequencies with a dict O(n).
3. If the frequency dicts are equal, they're anagrams.
4. Return False early if lengths differ.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that finds the missing number in an array from 0 to n.

Explanation:
I can use the mathematical sum formula.
1. The expected sum from 0 to n is n*(n+1)//2.
2. Sum the actual numbers in the array.
3. The difference is the missing number.
4. This is O(n) time and O(1) space, no extra data structures needed.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that counts word frequencies in a text.

Explanation:
I'll split the text into words, normalize them, and count.
1. Split by whitespace and remove punctuation.
2. Convert to lowercase for case-insensitive counting.
3. Use a dict to store word->count.
4. Return the dict sorted by frequency descending.
5. Handle empty input gracefully.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Explanation:
This is a classic Python mutable default argument bug.
1. Default arguments are evaluated once at function definition time.
2. All calls that use the default will share the same list.
3. So add_item(1) returns [1], add_item(2) returns [1,2], not [2].
4. Fix: use None as default and create a new list inside.

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Explanation:
Let me analyze the bug step by step.
1. The problem: numbers divisible by both 3 and 5 should print 'FizzBuzz'.
2. The current code uses elif, so when i % 3 == 0 is True, it prints 'Fizz' and skips the i % 5 check.
3. This means i=15 prints 'Fizz' instead of 'FizzBuzz'.
4. Fix: check the combined condition first (i % 15 == 0 or i % 3 == 0 and i % 5 == 0).

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Design an LRU (Least Recently Used) cache.

Explanation:
An LRU cache needs O(1) get and put operations.
1. I'll use a dict for key-value lookups and a doubly-linked list for order.
2. The dict maps keys to nodes in the linked list.
3. On get: move accessed node to head (most recent).
4. On put: add new node to head, evict tail if over capacity.
5. Using a sentinel head and tail simplifies edge cases.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function to reverse a linked list.

Output:
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

# Using dict as node for testing
n3 = {'val': 3, 'next': None}
n2 = {'val': 2, 'next': n3}
n1 = {'val': 1, 'next': n2}
reversed_head = reverse_linked_list(n1)
assert reversed_head['val'] == 3
assert reversed_head['next']['val'] == 2
assert reversed_head['next']['next']['val'] == 1


Input: Write a function that checks if a string is a palindrome.

Explanation:
A palindrome reads the same forwards and backwards.
1. I'll use two pointers: one at start, one at end.
2. While left < right, I compare characters and move inward.
3. If any mismatch, it's not a palindrome.
4. If all match, it is a palindrome.
5. I'll skip non-alphanumeric characters for a more robust solution.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that finds two numbers in a list that add up to a target sum.

Explanation:
Let me solve this step by step.
1. I need to find two numbers in the array that sum to target.
2. A brute force approach would check every pair O(n²), but I can do better.
3. I'll use a hash map to store numbers I've seen and check if target - current exists.
4. This gives O(n) time and O(n) space, which is optimal.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that finds the maximum sum of any contiguous subarray (Kadane's algorithm).

Output:
def max_subarray(nums):
    best = nums[0]
    current = nums[0]
    for n in nums[1:]:
        current = max(n, current + n)
        best = max(best, current)
    return best


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that checks if a string of brackets is valid.

Explanation:
I'll use a stack for this classic problem.
1. Map closing brackets to their corresponding opening brackets.
2. Iterate through the string.
3. If it's an opening bracket, push onto stack.
4. If it's a closing bracket, check if the top of stack matches.
5. If not, it's invalid.
6. At the end, the stack should be empty.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that finds the maximum sum of any contiguous subarray (Kadane's algorithm).

Output:
def max_subarray(nums):
    best = nums[0]
    current = nums[0]
    for n in nums[1:]:
        current = max(n, current + n)
        best = max(best, current)
    return best


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that performs binary search on a sorted list.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that performs binary search on a sorted list.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function to reverse a linked list.

Output:
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

# Using dict as node for testing
n3 = {'val': 3, 'next': None}
n2 = {'val': 2, 'next': n3}
n1 = {'val': 1, 'next': n2}
reversed_head = reverse_linked_list(n1)
assert reversed_head['val'] == 3
assert reversed_head['next']['val'] == 2
assert reversed_head['next']['next']['val'] == 1


Input: Write a function that performs binary search on a sorted list.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that finds the maximum sum of any contiguous subarray (Kadane's algorithm).

Output:
def max_subarray(nums):
    best = nums[0]
    current = nums[0]
    for n in nums[1:]:
        current = max(n, current + n)
        best = max(best, current)
    return best


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function to reverse a linked list.

Output:
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

# Using dict as node for testing
n3 = {'val': 3, 'next': None}
n2 = {'val': 2, 'next': n3}
n1 = {'val': 1, 'next': n2}
reversed_head = reverse_linked_list(n1)
assert reversed_head['val'] == 3
assert reversed_head['next']['val'] == 2
assert reversed_head['next']['next']['val'] == 1


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that performs binary search on a sorted list.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input: Write a function that performs binary search on a sorted list.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function to reverse a linked list.

Output:
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

# Using dict as node for testing
n3 = {'val': 3, 'next': None}
n2 = {'val': 2, 'next': n3}
n1 = {'val': 1, 'next': n2}
reversed_head = reverse_linked_list(n1)
assert reversed_head['val'] == 3
assert reversed_head['next']['val'] == 2
assert reversed_head['next']['next']['val'] == 1


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function to reverse a linked list.

Output:
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

# Using dict as node for testing
n3 = {'val': 3, 'next': None}
n2 = {'val': 2, 'next': n3}
n1 = {'val': 1, 'next': n2}
reversed_head = reverse_linked_list(n1)
assert reversed_head['val'] == 3
assert reversed_head['next']['val'] == 2
assert reversed_head['next']['next']['val'] == 1


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input:
Find the bug: def add_item(item, items=[]):
    items.append(item)
    return items

Output:
def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

assert add_item(1) == [1]
assert add_item(2) == [2]
assert add_item(3, [0]) == [0,3]


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that performs binary search on a sorted list.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function to reverse a linked list.

Output:
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

# Using dict as node for testing
n3 = {'val': 3, 'next': None}
n2 = {'val': 2, 'next': n3}
n1 = {'val': 1, 'next': n2}
reversed_head = reverse_linked_list(n1)
assert reversed_head['val'] == 3
assert reversed_head['next']['val'] == 2
assert reversed_head['next']['next']['val'] == 1


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that finds the maximum sum of any contiguous subarray (Kadane's algorithm).

Output:
def max_subarray(nums):
    best = nums[0]
    current = nums[0]
    for n in nums[1:]:
        current = max(n, current + n)
        best = max(best, current)
    return best


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that finds the maximum sum of any contiguous subarray (Kadane's algorithm).

Output:
def max_subarray(nums):
    best = nums[0]
    current = nums[0]
    for n in nums[1:]:
        current = max(n, current + n)
        best = max(best, current)
    return best


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Design an LRU (Least Recently Used) cache.

Output:
class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = {}
        self.head = {'key': None, 'val': None, 'prev': None, 'next': None}
        self.tail = {'key': None, 'val': None, 'prev': self.head, 'next': None}
        self.head['next'] = self.tail

    def _remove(self, node):
        node['prev']['next'] = node['next']
        node['next']['prev'] = node['prev']

    def _add_to_head(self, node):
        node['next'] = self.head['next']
        node['prev'] = self.head
        self.head['next']['prev'] = node
        self.head['next'] = node

    def get(self, key):
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self._remove(node)
        self._add_to_head(node)
        return node['val']

    def put(self, key, value):
        if key in self.cache:
            node = self.cache[key]
            node['val'] = value
            self._remove(node)
            self._add_to_head(node)
        else:
            node = {'key': key, 'val': value, 'prev': None, 'next': None}
            self.cache[key] = node
            self._add_to_head(node)
            if len(self.cache) > self.cap:
                lru = self.tail['prev']
                self._remove(lru)
                del self.cache[lru['key']]

cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
assert cache.get(1) == 1
cache.put(3,3)
assert cache.get(2) == -1
cache.put(4,4)
assert cache.get(1) == -1
assert cache.get(3) == 3
assert cache.get(4) == 4


Input: Write a function that performs binary search on a sorted list.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input: Write a function that merges overlapping intervals.

Output:
def merge_intervals(intervals):
    if not intervals:
        return []
    intervals.sort(key=lambda x: x[0])
    merged = [intervals[0]]
    for start, end in intervals[1:]:
        if start <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], end))
        else:
            merged.append([start, end])
    return merged


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that checks if two strings are anagrams.

Output:
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] < 0:
            return False
    return True

assert is_anagram('listen', 'silent') == True
assert is_anagram('hello', 'world') == False
assert is_anagram('', '') == True
assert is_anagram('aabb', 'bbaa') == True


Input: Write a function that checks if a string of brackets is valid.

Output:
def valid_parentheses(s):
    pairs = {')': '(', '}': '{', ']': '['}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return len(stack) == 0

assert valid_parentheses('()') == True
assert valid_parentheses('()[]{}') == True
assert valid_parentheses('(]') == False
assert valid_parentheses('([)]') == False
assert valid_parentheses('{[]}') == True


Input: Write a function that performs binary search on a sorted list.

Output:
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

assert binary_search([1,2,3,4,5], 3) == 2
assert binary_search([1,2,3,4,5], 6) == -1
assert binary_search([], 1) == -1
assert binary_search([1], 1) == 0


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function that finds two numbers in a list that add up to a target sum.

Output:
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        complement = target - n
        if complement in seen:
            return [seen[complement], i]
        seen[n] = i
    return []


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input: Write a function that reverses a string in-place.

Output:
def reverse_string(s):
    chars = list(s)
    left, right = 0, len(chars) - 1
    while left < right:
        chars[left], chars[right] = chars[right], chars[left]
        left += 1
        right -= 1
    return ''.join(chars)

assert reverse_string('hello') == 'olleh'
assert reverse_string('') == ''
assert reverse_string('a') == 'a'
assert reverse_string('ab') == 'ba'


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that counts word frequencies in a text.

Output:
def word_count(text):
    import re
    words = re.findall(r'\w+', text.lower())
    freq = {}
    for w in words:
        freq[w] = freq.get(w, 0) + 1
    return dict(sorted(freq.items(), key=lambda x: -x[1]))

assert word_count('hello world hello') == {'hello': 2, 'world': 1}
assert word_count('') == {}
assert word_count('Go go go') == {'go': 3}


Input:
Find and fix the bug in this FizzBuzz implementation: for i in range(1, 16):
    if i % 3 == 0:
        print('Fizz')
    elif i % 5 == 0:
        print('Buzz')
    else:
        print(i)

Output:
def fizzbuzz(n):
    for i in range(1, n+1):
        if i % 15 == 0:
            print('FizzBuzz')
        elif i % 3 == 0:
            print('Fizz')
        elif i % 5 == 0:
            print('Buzz')
        else:
            print(i)

# Expected output for n=15
# 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,FizzBuzz


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True


Input: Write a function to reverse a linked list.

Output:
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

# Using dict as node for testing
n3 = {'val': 3, 'next': None}
n2 = {'val': 2, 'next': n3}
n1 = {'val': 1, 'next': n2}
reversed_head = reverse_linked_list(n1)
assert reversed_head['val'] == 3
assert reversed_head['next']['val'] == 2
assert reversed_head['next']['next']['val'] == 1


Input: Write a function that finds the missing number in an array from 0 to n.

Output:
def find_missing(nums):
    n = len(nums)
    expected = n * (n + 1) // 2
    actual = sum(nums)
    return expected - actual

assert find_missing([3,0,1]) == 2
assert find_missing([0,1]) == 2
assert find_missing([9,6,4,2,3,5,7,0,1]) == 8
assert find_missing([0]) == 1


Input: Write a function that checks if a string is a palindrome.

Output:
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome('racecar') == True
assert is_palindrome('hello') == False
assert is_palindrome('A man, a plan, a canal: Panama') == True
assert is_palindrome('') == True