Autocoder

Visa coding round questions with solutions

Last updated 2026-11-19

Visa engineering assessments are commonly described as medium-difficulty data structures and algorithms problems, with design-style questions and occasionally SQL. As a payments company, domain-flavoured problems such as card-number validation or rate counting are natural practice. This set follows that style with nine coding problems and one MCQ. None is a recalled question.

Each answer has the approach, complexity, the usual mistake and runnable Python and Java. For the interviews, see Visa interview questions.

StyleMedium DSA, small design problems, SQL
Languages herePython, Java, SQL
Problems9 coding, 1 MCQ-style
LevelEasy to hard

How to approach this set

Medium problems are decided by choosing the right structure: a heap for merging, union-find for connectivity, a deque for a sliding time window. Name the structure and the invariant it keeps before writing code.

Design-flavoured problems such as the hit counter test whether you handle edge cases like many hits in the same second. Review the habits in how to crack an online assessment and DSA coding rounds, and revisit dynamic programming interview questions for subset-sum style problems.

Visa coding round questions with solutions: questions with worked answers

  1. 1

    Validate a card number with the Luhn algorithm.

    easy

    From the rightmost digit, double every second digit moving left (the second from the right, the fourth, and so on). If doubling gives more than 9, subtract 9. Add all the digits; the number is valid if the total is divisible by 10. Time O(n), space O(1). For example 79927398713 is valid and 4539148803436468 is not, because it differs from a valid number only in its last digit. Mistakes: doubling from the left, which fails for odd-length numbers, and doubling the check digit itself. Luhn catches typing errors, not fraud.

    python
    def luhn(number):
        total = 0
        for i, ch in enumerate(reversed(number)):
            d = int(ch)
            if i % 2 == 1:
                d *= 2
                if d > 9:
                    d -= 9
            total += d
        return total % 10 == 0
    java
    class Solution {
        static boolean luhn(String number) {
            int total = 0;
            for (int i = 0; i < number.length(); i++) {
                int d = number.charAt(number.length() - 1 - i) - '0';
                if (i % 2 == 1) { d *= 2; if (d > 9) d -= 9; }
                total += d;
            }
            return total % 10 == 0;
        }
    }
  2. 2

    Merge k sorted linked lists into one sorted list.

    hard

    Push the head of each list into a min-heap keyed by value, with an index as a tie-breaker so nodes are never compared directly. Pop the smallest, append it to the result and push its successor. Time O(N log k) for N total nodes, space O(k). Divide and conquer, merging lists in pairs, gives the same time with O(1) extra space. Mistake: omitting the tie-breaker, which raises an error in Python when two values are equal.

    python
    import heapq
    class ListNode:
        def __init__(self, val=0, next=None):
            self.val, self.next = val, next
    
    def merge_k(lists):
        h = [(n.val, i, n) for i, n in enumerate(lists) if n]
        heapq.heapify(h)
        dummy = tail = ListNode()
        while h:
            _, i, n = heapq.heappop(h)
            tail.next = n
            tail = n
            if n.next:
                heapq.heappush(h, (n.next.val, i, n.next))
        return dummy.next
    java
    import java.util.*;
    class Solution {
        static class ListNode { int val; ListNode next; ListNode(int v) { val = v; } }
        static ListNode mergeK(ListNode[] lists) {
            PriorityQueue<ListNode> h = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
            for (ListNode n : lists) if (n != null) h.add(n);
            ListNode dummy = new ListNode(0), tail = dummy;
            while (!h.isEmpty()) {
                ListNode n = h.poll();
                tail.next = n;
                tail = n;
                if (n.next != null) h.add(n.next);
            }
            return dummy.next;
        }
    }
  3. 3

    Search a target in a matrix where each row is sorted and each row's first value exceeds the previous row's last.

    medium

    Treat the matrix as one sorted array of m x n elements and binary search over indices 0 to mn - 1, mapping index k to row k // n and column k % n. Time O(log(mn)), space O(1). Mistake: confusing this with the matrix where only rows and columns are sorted independently; that needs the staircase search from a corner in O(m + n).

    python
    def search_matrix(m, t):
        R, C = len(m), len(m[0])
        lo, hi = 0, R * C - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            v = m[mid // C][mid % C]
            if v == t: return True
            if v < t: lo = mid + 1
            else: hi = mid - 1
        return False
    java
    class Solution {
        static boolean searchMatrix(int[][] m, int t) {
            int R = m.length, C = m[0].length, lo = 0, hi = R * C - 1;
            while (lo <= hi) {
                int mid = (lo + hi) / 2, v = m[mid / C][mid % C];
                if (v == t) return true;
                if (v < t) lo = mid + 1; else hi = mid - 1;
            }
            return false;
        }
    }
  4. 4

    Jump game: each value is the maximum jump length from that index. Can you reach the last index?

    medium

    Greedy: track the farthest index reachable so far. Walk left to right; if the current index is beyond the farthest reach, you are stuck and return false; otherwise update the farthest with i + a[i]. Time O(n), space O(1). A DP over all positions is O(n^2). Mistake: stopping when you meet a zero, which is fine if a previous jump can clear it.

    python
    def can_jump(a):
        far = 0
        for i, x in enumerate(a):
            if i > far:
                return False
            far = max(far, i + x)
        return True
    java
    class Solution {
        static boolean canJump(int[] a) {
            int far = 0;
            for (int i = 0; i < a.length; i++) {
                if (i > far) return false;
                far = Math.max(far, i + a[i]);
            }
            return true;
        }
    }
  5. 5

    Partition equal subset sum: can the array be split into two subsets with equal sums?

    medium

    If the total is odd, the answer is no. Otherwise it is the subset-sum problem for a target of total / 2. Use a boolean array dp over sums, and for each number update from the target downwards so each number is used once. Time O(n x target), space O(target). Updating upwards allows reuse of the same number, which is the classic bug (it solves the unbounded version).

    python
    def can_partition(a):
        total = sum(a)
        if total % 2:
            return False
        t = total // 2
        dp = [False] * (t + 1)
        dp[0] = True
        for x in a:
            for s in range(t, x - 1, -1):
                dp[s] = dp[s] or dp[s - x]
        return dp[t]
    java
    class Solution {
        static boolean canPartition(int[] a) {
            int total = 0;
            for (int x : a) total += x;
            if (total % 2 != 0) return false;
            int t = total / 2;
            boolean[] dp = new boolean[t + 1];
            dp[0] = true;
            for (int x : a)
                for (int s = t; s >= x; s--) dp[s] = dp[s] || dp[s - x];
            return dp[t];
        }
    }
  6. 6

    Design a hit counter that returns the number of hits in the last 300 seconds.

    medium

    Store timestamps in a queue (deque). On hit(t), append t. On getHits(t), pop from the front while the front timestamp is at or before t - 300, then return the queue size. Each timestamp is added and removed once, so operations are amortised O(1), with space proportional to hits in the window. For very high traffic, use 300 buckets indexed by t % 300 with the bucket's timestamp, which gives O(1) space.

    python
    from collections import deque
    class HitCounter:
        def __init__(self):
            self.q = deque()
        def hit(self, t):
            self.q.append(t)
        def get_hits(self, t):
            while self.q and self.q[0] <= t - 300:
                self.q.popleft()
            return len(self.q)
    java
    import java.util.*;
    class HitCounter {
        private final Deque<Integer> q = new ArrayDeque<>();
        void hit(int t) { q.addLast(t); }
        int getHits(int t) {
            while (!q.isEmpty() && q.peekFirst() <= t - 300) q.pollFirst();
            return q.size();
        }
    }
  7. 7

    Number of provinces: given an n x n matrix where m[i][j] = 1 means cities i and j are directly connected, count the groups of connected cities.

    medium

    Use union-find. Start with each city in its own set, union cities i and j whenever m[i][j] is 1, and each successful union reduces the component count by one. With path compression and union by size each operation is nearly O(1), so the total is O(n^2) for scanning the matrix. DFS over the matrix gives the same result. Mistake: scanning both triangles and double-counting a union (harmless with union-find but wasteful).

    python
    def provinces(m):
        n = len(m)
        p = list(range(n))
        def find(x):
            while p[x] != x:
                p[x] = p[p[x]]
                x = p[x]
            return x
        count = n
        for i in range(n):
            for j in range(i + 1, n):
                if m[i][j]:
                    a, b = find(i), find(j)
                    if a != b:
                        p[a] = b
                        count -= 1
        return count
    java
    class Solution {
        static int[] p;
        static int find(int x) {
            while (p[x] != x) { p[x] = p[p[x]]; x = p[x]; }
            return x;
        }
        static int provinces(int[][] m) {
            int n = m.length, count = n;
            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(i), b = find(j);
                        if (a != b) { p[a] = b; count--; }
                    }
            return count;
        }
    }
  8. 8

    Decode a string such as 3[a2[c]] into accaccacc.

    medium

    Use a stack. Scan characters: accumulate digits into a count, on '[' push the current string and the count and reset, on ']' pop and set the current string to the previous string plus the current string repeated count times, and otherwise append letters. Time is proportional to the output length, space O(depth). The usual bug is parsing multi-digit counts as single digits (the count 12 must be built as 1 then 12).

    python
    def decode(s):
        stack, cur, num = [], "", 0
        for ch in s:
            if ch.isdigit():
                num = num * 10 + int(ch)
            elif ch == '[':
                stack.append((cur, num))
                cur, num = "", 0
            elif ch == ']':
                prev, k = stack.pop()
                cur = prev + cur * k
            else:
                cur += ch
        return cur
    java
    import java.util.*;
    class Solution {
        static String decode(String s) {
            Deque<String> strs = new ArrayDeque<>();
            Deque<Integer> nums = new ArrayDeque<>();
            StringBuilder cur = new StringBuilder();
            int num = 0;
            for (char ch : s.toCharArray()) {
                if (Character.isDigit(ch)) num = num * 10 + (ch - '0');
                else if (ch == '[') { strs.push(cur.toString()); nums.push(num); cur = new StringBuilder(); num = 0; }
                else if (ch == ']') {
                    StringBuilder t = new StringBuilder(strs.pop());
                    for (int k = nums.pop(); k > 0; k--) t.append(cur);
                    cur = t;
                } else cur.append(ch);
            }
            return cur.toString();
        }
    }
  9. 9

    SQL: compute each merchant's approval rate, the share of transactions with status 'APPROVED'.

    easy

    Use conditional aggregation: count the approved rows with SUM(CASE ...) and divide by COUNT(*). Cast to a decimal first, or integer division returns 0 in many databases. Group by merchant, and consider a minimum transaction count so tiny merchants do not dominate a ranking.

    sql
    SELECT merchant_id,
           ROUND(100.0 * SUM(CASE WHEN status = 'APPROVED' THEN 1 ELSE 0 END) / COUNT(*), 2) AS approval_pct
    FROM Transactions
    GROUP BY merchant_id;
  10. 10

    CS MCQ: what is the amortised time per operation of union-find with path compression and union by rank?

    hard

    O(alpha(n)), where alpha is the inverse Ackermann function, which is at most 4 for any practical n, so it is effectively constant. Path compression alone gives O(log n) amortised, and union by rank alone gives O(log n) per operation. Option sets often list O(1), O(log n) and O(alpha(n)); choose the last if both optimisations are mentioned.

Frequently asked questions

How difficult are Visa coding questions?

They are commonly described as medium difficulty with occasional harder problems on graphs, DP and heaps.

Is the Luhn algorithm part of the test?

Not as a known question. It is included here as domain-flavoured practice because it exercises string and digit handling.

Does the test include SQL?

Some roles are reported to include SQL. Practise conditional aggregation and window functions.

Are these the real questions?

No. They are original practice problems in the style of the topics the round commonly covers.

Related guides

More in Company Interview Questions

See all in this section