Skip to main content

Posts

Prefix Sums for Range Sum Queries in Java and Python

Build a prefix sum array in O(n) time, then answer each half-open range sum query in O(1) time in Java and Python. Problem and input contract Build a prefix array for a fixed sequence of n signed 32-bit integers. Each query uses zero-based bounds 0 ≤ left ≤ right ≤ n and returns the sum of elements from left up to right exclusive. For [3, −2, 5, 1] , [1, 3) returns 3 and [0, 4) returns 7 . The empty array supports [0, 0) , which returns 0 . Two maximum Java int values sum to 4294967294 . Worked example For [3, −2, 5, 1], the sum over [1, 3) is 3. Start with 0, then append 3, 1, 6, and 7. For [1, 3), subtract prefix[1] = 3 from prefix[3] = 6. The result is 3, the sum of −2 and 5. How the solution works Each prefix stores the sum before its index. Subtract the prefix ending before left from the prefix ending before right. Keep the initial zero so a range starting at index 0 uses the same subtraction. Require 0 ≤ left ≤ right ≤ n. Java uses long because sums can exceed int even wh...
Recent posts

Merge Overlapping Intervals in Java and Python

Merge overlapping closed intervals with a sort-and-scan algorithm. See how Java and Python handle touching endpoints, nesting, and empty input. Problem and input contract Given pairs (start, end) with start ≤ end , return sorted, disjoint closed intervals with the same union. The functions preserve the input. [(5, 7), (1, 3), (3, 6)] gives [(1, 7)] . [(1, 9), (2, 4), (12, 12)] gives [(1, 9), (12, 12)] . Empty input gives an empty result. Worked example [(5, 7), (1, 3), (3, 6)] merges to [(1, 7)]. After sorting, process (1, 3) first. The next interval starts at 3, so it touches the first and extends it to (1, 6). The last interval starts at 5 and extends the end to 7. How the solution works Sorting by start means the last merged interval is the only candidate for overlap with the next input interval. Using max preserves the existing end when the new interval is contained. These are closed intervals, so equality counts as overlap. Sorting by start means a gap closes off all earlier ...

Unweighted Shortest Paths with BFS in Java and Python

Find the shortest distance from a source to every reachable vertex in an unweighted graph using breadth-first search in Java and Python. Problem and input contract Provide an adjacency map from string vertex IDs to lists of outgoing neighbors and a non-null starting ID. Use both directions for undirected edges. A missing key means the vertex has no outgoing edges. The result maps each reachable vertex to its minimum edge count. For A → B, C and B → D , with C → D , the distances are A: 0, B: 1, C: 1, D: 2 . An isolated A returns only A: 0 . With A → A, B , the self-loop leaves A at 0 and B is 1 away. Worked example If A links to B and C, and B links to D, the distance from A to D is 2. Queue A with distance 0. Processing A discovers B and C at distance 1. When B is removed, discover D at distance 2. If C also points to D, skip it because D already has a shortest distance. How the solution works The queue visits vertices in layers. The first discovery gives the fewest edges. Marking ...

Reverse a Singly Linked List in Java and Python

Reverse a singly linked list in place with three references, O(n) time, and O(1) extra space in Java and Python. Problem and input contract Pass the head of a finite, acyclic list of nodes with a value and a next reference. The function rewires the original nodes and returns the new head. 1 → 2 → 3 becomes 3 → 2 → 1 . An empty list returns null or None. The list 8 returns the same node. Worked example 1 → 2 → 3 becomes 3 → 2 → 1. At node 1, save node 2 before pointing 1 to null. At node 2, save node 3 before pointing 2 back to 1. At node 3, point it back to 2. The saved following reference is null, so return 3. How the solution works Save the next node before reversing its pointer. The previous pointer leads to the reversed prefix and current leads to the unprocessed suffix. The temporary following variable preserves the only link to the remaining nodes. The loop changes the original list, so callers should keep the returned head. Python solution class Node: def __init__(self,...

Climbing Stairs in Java and Python

Count the ways to climb stairs with one- and two-step moves using rolling dynamic programming in Java and Python. Problem and input contract The input is an integer n ≥ 0 . Return the exact number of ordered move sequences that land on step n . For example, a move of one followed by a move of two differs from the reverse order. n = 0 gives 1 (the empty sequence). n = 1 gives 1 . n = 3 gives 3 . Worked example For n = 3, the sequences are 1+1+1, 1+2 and 2+1. There is one way to stand at step 0 and one way to reach step 1. Step 2 has two paths. Step 3 has three paths, because it can follow either of the two paths to step 2 or the one path to step 1. How the solution works A path ends with either a one-step or a two-step move. Adding the counts for those two preceding positions covers all paths exactly once. There is one empty path for zero stairs. The two running counts are enough because each new value depends only on the previous two. Java uses BigInteger for exact results. Both ...

Move Zeroes In Place in Java and Python

Move zeroes to the end of an array in place while preserving the order of nonzero values. Learn the two-pointer solution in Java and Python. Problem and input contract Pass a mutable sequence of integers. Both implementations modify it in place and return no value. The sequence retains its original length, with all nonzero values in their original relative order. [0, 3, 0, 2] becomes [3, 2, 0, 0] . [0, 0] and [-2, 4] stay unchanged. An empty array remains empty. Worked example [0, 3, 0, 2] becomes [3, 2, 0, 0]. Skip the first 0. Copy 3 into index 0, skip the next 0, then copy 2 into index 1. At that point write is 2, so fill indices 2 and 3 with zero. How the solution works The write index never moves ahead of the read index. Every nonzero value is copied forward in encounter order, then the remaining cells are filled with zeros. Each write lands at or before the position being read. This keeps unread values intact and preserves the original order of the nonzero numbers. Python so...

Daily Coding Problem: Find the First Occurrence with Binary Search

Finding a value in a sorted array is a familiar binary-search problem. Finding its first occurrence adds a small but important requirement: when the middle value matches, you cannot stop. An earlier copy may still be waiting on the left. In this exercise, we will build one iterative solution in Python and Java, trace every boundary change, explain why it is correct, and test the cases that commonly cause off-by-one errors. The same idea also finds the insertion position for a missing value. The problem and input contract Given an integer array sorted in nondecreasing order and an integer target, return the zero-based index of the target's first occurrence. Return -1 when it is absent. Repeated values are allowed. The input must already be sorted, and the algorithm does not modify it. For [1, 2, 2, 2, 5] and target 2 , the answer is 1 , not 2 or 3. For the same array and target 4 , the answer is -1 . An empty array also returns -1 . Both implementations expect an array or lis...