Autocoder

Target Coding Round Questions

Last updated 2026-11-19

Retail makes good algorithm problems: finding two gifts that match a budget, the best day to buy from a price history, the top sellers, the least shipping capacity that meets a deadline, the number of ways to make change. This page works through twelve such practice problems with solutions in Python and Java, complexity and the mistakes that lose marks.

They are practice problems in the style of coding assessments, not copies of any test. Use them with Target interview questions and the DSA coding round guide.

Languages herePython, Java, SQL
ThemesTwo pointers, heaps, binary search, DP, union-find
LevelEasy to hard

How to approach these problems

Rewrite the retail story as a standard pattern in one sentence, state the brute force and its cost, then improve it. Retail inputs are large, so aim for O(n log n) or better and watch for integer overflow when summing prices or quantities.

Hiring status

We hold no sourced facts about Target tests, drives, openings or cutoffs, so none are stated. Use the company's own careers site for current information.

Target Coding Round Questions: questions with worked answers

  1. 1

    Gift budget: given sorted item prices, find two items whose prices add up exactly to the budget.

    easy

    Two pointers from both ends: if the sum is too small move the left pointer right, if too large move the right pointer left. O(n) time, O(1) space given sorted input. Mistake: using the hash-map method on sorted input (correct but wastes space), and returning the same item twice by letting the pointers cross.

    python
    def gift_pair(prices, budget):
        i, j = 0, len(prices) - 1
        while i < j:
            s = prices[i] + prices[j]
            if s == budget:
                return prices[i], prices[j]
            if s < budget:
                i += 1
            else:
                j -= 1
        return None
    
    print(gift_pair([5, 10, 25, 40, 60], 65))  # (5, 60)
  2. 2

    Best day to buy and sell: given daily prices, find the maximum profit from one buy and one later sell.

    easy

    Scan once keeping the lowest price so far and the best profit if you sold today. O(n) time, O(1) space. Return 0 if prices only fall. Mistake: the nested-loop version (O(n squared)), and selling before buying by taking the global minimum and maximum independently.

    python
    def max_profit(prices):
        low, best = float('inf'), 0
        for p in prices:
            low = min(low, p)
            best = max(best, p - low)
        return best
    
    print(max_profit([7, 1, 5, 3, 6, 4]))  # 5
  3. 3

    Top K selling products from (product, quantity) sale lines.

    medium

    Aggregate quantity per product with a map, then take the k largest with a min-heap of size k. O(n + m log k) for m distinct products. Mistake: sorting all products when k is small, and ignoring ties; define a deterministic tie-break, for example the product id.

    python
    import heapq
    from collections import defaultdict
    
    def top_k(sales, k):
        total = defaultdict(int)
        for product, qty in sales:
            total[product] += qty
        return heapq.nsmallest(k, total.items(), key=lambda x: (-x[1], x[0]))
    
    print(top_k([("pen", 5), ("bag", 9), ("pen", 7), ("cup", 3)], 2))  # [('pen', 12), ('bag', 9)]
  4. 4

    Merge k sorted lists of store inventory counts into one sorted list.

    medium

    Put the first element of each list in a min-heap with its list and position; repeatedly pop the smallest and push the next from the same list. O(N log k) for N total elements. Mistake: concatenating and sorting, which is O(N log N) and ignores sortedness, and comparing list objects when values tie (include an index in the tuple).

    python
    import heapq
    
    def merge_k(lists):
        heap = [(l[0], i, 0) for i, l in enumerate(lists) if l]
        heapq.heapify(heap)
        out = []
        while heap:
            val, i, j = heapq.heappop(heap)
            out.append(val)
            if j + 1 < len(lists[i]):
                heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
        return out
    
    print(merge_k([[1, 4, 7], [2, 5], [3, 6, 9]]))  # [1, 2, 3, 4, 5, 6, 7, 9]
  5. 5

    Shipping capacity: packages with given weights must ship in order within D days. Find the least ship capacity.

    medium

    Binary search on the answer between the heaviest package and the total weight. For a candidate capacity, simulate loading greedily and count days; if it fits in D days, try smaller, otherwise larger. O(n log(sum of weights)). Mistake: starting the lower bound at 1 (a package may not fit) and splitting packages.

    python
    def ship_capacity(weights, days):
        lo, hi = max(weights), sum(weights)
        while lo < hi:
            mid = (lo + hi) // 2
            need, load = 1, 0
            for w in weights:
                if load + w > mid:
                    need += 1
                    load = 0
                load += w
            if need <= days:
                hi = mid
            else:
                lo = mid + 1
        return lo
    
    print(ship_capacity([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5))  # 15
  6. 6

    Longest run of consecutive order numbers in an unsorted array.

    medium

    Put all numbers in a set; for each number that has no predecessor (n - 1 not in the set), count upward while n + 1 exists. Each number is visited at most twice, so O(n) time and O(n) space. Mistake: sorting (O(n log n)), or starting a count from every number, which becomes O(n squared).

    python
    def longest_run(a):
        s, best = set(a), 0
        for n in s:
            if n - 1 not in s:
                m = n
                while m + 1 in s:
                    m += 1
                best = max(best, m - n + 1)
        return best
    
    print(longest_run([100, 4, 200, 1, 3, 2]))  # 4
  7. 7

    Moving average of the last k sales from a stream.

    medium

    Keep a deque of the last k values and a running sum: add the new value, drop the oldest when the window is full and divide by the current size. O(1) per update, O(k) space. Mistake: recomputing the sum over the window each time, and dividing by k before the window is full.

    python
    from collections import deque
    
    class MovingAverage:
        def __init__(self, k):
            self.k, self.q, self.total = k, deque(), 0
    
        def next(self, x):
            self.q.append(x)
            self.total += x
            if len(self.q) > self.k:
                self.total -= self.q.popleft()
            return self.total / len(self.q)
    
    m = MovingAverage(3)
    print([m.next(x) for x in (1, 10, 3, 5)])  # [1.0, 5.5, 4.666..., 6.0]
  8. 8

    Number of ways to make change for an amount using unlimited coins (order does not matter).

    medium

    Dynamic programming over coins in the outer loop and amounts in the inner loop: ways[a] += ways[a - coin]. Putting coins in the outer loop counts combinations, not permutations. O(coins * amount) time, O(amount) space. Mistake: swapping the loops, which counts ordered sequences (1+2 and 2+1 separately).

    python
    def ways(coins, amount):
        dp = [1] + [0] * amount
        for c in coins:
            for a in range(c, amount + 1):
                dp[a] += dp[a - c]
        return dp[amount]
    
    print(ways([1, 2, 5], 5))  # 4
  9. 9

    Groups of connected stores: given a matrix where cell (i, j) is 1 if stores i and j are connected, count the groups.

    medium

    Union-find: start with each store in its own set, union every connected pair, and count roots. With path compression and union by size each operation is nearly constant, so O(n squared) for the matrix scan. DFS or BFS gives the same answer. Mistake: counting only direct neighbours and missing indirect connections (a connects to b, b connects to c).

    java
    public class Groups {
        static int find(int[] p, int x) {
            while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; }
            return x;
        }
        public static int count(int[][] m) {
            int n = m.length, groups = n;
            int[] p = new int[n];
            for (int i = 0; i < n; i++) p[i] = i;
            for (int i = 0; i < n; i++)
                for (int j = i + 1; j < n; j++)
                    if (m[i][j] == 1) {
                        int a = find(p, i), b = find(p, j);
                        if (a != b) { p[a] = b; groups--; }
                    }
            return groups;
        }
    }
  10. 10

    SQL: products whose stock is below their reorder level, with the shortfall, including products that have no inventory row.

    medium

    LEFT JOIN products to inventory and treat a missing row as zero stock with COALESCE, then keep rows below the reorder level. Mistake: an inner join, which silently drops products that have never been stocked, which are exactly the ones needing a reorder.

    sql
    SELECT p.id, p.name, p.reorder_level - COALESCE(i.on_hand, 0) AS shortfall
    FROM products p
    LEFT JOIN inventory i ON i.product_id = p.id
    WHERE COALESCE(i.on_hand, 0) < p.reorder_level;
  11. 11

    Maximum profit with at most k transactions on a price history.

    hard

    DP with two arrays: buy[j] is the best balance after the j-th buy and sell[j] after the j-th sell. For each price update j from 1 to k: buy[j] = max(buy[j], sell[j-1] - price), sell[j] = max(sell[j], buy[j] + price). O(n k) time, O(k) space. If k is at least n/2, it equals the unlimited-transactions answer, summing every positive rise. Mistake: skipping the large-k shortcut, so a huge k allocates and loops far more than needed; cap k at n // 2.

    python
    def max_profit_k(k, prices):
        if not prices or k == 0:
            return 0
        buy = [float('-inf')] * (k + 1)
        sell = [0] * (k + 1)
        for p in prices:
            for j in range(1, k + 1):
                buy[j] = max(buy[j], sell[j - 1] - p)
                sell[j] = max(sell[j], buy[j] + p)
        return sell[k]
    
    print(max_profit_k(2, [3, 2, 6, 5, 0, 3]))  # 7

Frequently asked questions

What problem types suit Target-style assessments?

Arrays and hashing, two pointers, heaps, binary search on the answer, basic dynamic programming and graph or union-find problems, with SQL as a supporting skill.

Python or Java?

Either. Python is shorter in a timed test; Java is fine, especially if you also face object-oriented design questions.

How should I practise time management?

Time yourself at 25 to 30 minutes per medium problem, write the brute force first and move on if stuck beyond ten minutes without progress.

Are these real Target questions?

No. They are practice problems written in the style of coding assessments, not copies of any test.

Is the assessment proctored?

We have no sourced proctoring details. Read the rules in your invitation, and see is it safe for what any assistant can and cannot do.

Related guides

More in Company Interview Questions

See all in this section