Autocoder

ServiceNow Coding Round Questions With Solutions

Last updated 2026-11-19

Reports of the ServiceNow online assessment describe two DSA questions plus MCQs, followed by live DSA coding in technical interviews. The eleven problems below are practice at that kind of level: standard medium problems on arrays, stacks, trees, graphs and backtracking, with the idea, code, complexity and a typical mistake.

They are practice problems, not real papers. For design and SQL questions see ServiceNow interview questions, and for the overall process read how to crack the ServiceNow interview.

Reported testTwo DSA questions plus MCQs (some reports)
Reported platformHackerRank

Format as commonly reported

Candidate reports cited in this site's ServiceNow process notes mention HackerRank, two DSA questions and MCQs on aptitude, DBMS and SQL. Formats change between years and roles, so read your own invitation. Tests reward correct, complete solutions, so write a working version first.

Hiring status

ServiceNow has a ServiceNow hiring page here. The only sourced hiring fact is a January 2026 report that the company plans to expand Hyderabad teams in 2026, with no counts or dates. For current roles, use the company's careers site.

ServiceNow Coding Round Questions With Solutions: questions with worked answers

  1. 1

    Min stack: push, pop, top and getMin in O(1).

    medium

    Store each element with the minimum so far, or keep a second stack of minimums. Push the new minimum onto the second stack only when the value is less than or equal to the current minimum; pop it when the popped value equals the minimum. Mistake: using strictly less-than, which breaks with duplicates of the minimum.

    python
    class MinStack:
        def __init__(self):
            self.s, self.m = [], []
        def push(self, x):
            self.s.append(x)
            if not self.m or x <= self.m[-1]:
                self.m.append(x)
        def pop(self):
            x = self.s.pop()
            if x == self.m[-1]:
                self.m.pop()
            return x
        def top(self):
            return self.s[-1]
        def get_min(self):
            return self.m[-1]
  2. 2

    Evaluate a reverse Polish notation expression.

    medium

    Use a stack: push numbers; on an operator pop the right operand then the left, apply it and push the result. Division truncates toward zero, so use int(a / b) in Python and not floor division. O(n). Mistake: reversing the operand order for subtraction and division.

    python
    def eval_rpn(tokens):
        st = []
        for t in tokens:
            if t in '+-*/' and len(t) == 1:
                b, a = st.pop(), st.pop()
                st.append(a + b if t == '+' else a - b if t == '-'
                          else a * b if t == '*' else int(a / b))
            else:
                st.append(int(t))
        return st[0]
  3. 3

    Number of provinces (connected groups) from an adjacency matrix.

    medium

    Use union-find over the n cities, merging any pair with a 1 in the matrix; the answer is the number of roots. Or run DFS from each unvisited city. O(n squared) for scanning the matrix. Mistake: counting only direct links and missing indirect connections.

    python
    def provinces(m):
        n = len(m)
        parent = list(range(n))
        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x
        for i in range(n):
            for j in range(i + 1, n):
                if m[i][j]:
                    parent[find(i)] = find(j)
        return len({find(i) for i in range(n)})
  4. 4

    Zigzag level order traversal of a binary tree.

    medium

    Do BFS by levels and reverse every other level's list (or append to the left for odd levels using a deque). O(n) time, O(width) space. Mistake: reversing the traversal order of children instead of the output list, which breaks the left-to-right order of the next level.

    python
    from collections import deque
    
    def zigzag(root):
        if not root:
            return []
        out, q, flip = [], deque([root]), False
        while q:
            level = []
            for _ in range(len(q)):
                n = q.popleft()
                level.append(n.val)
                if n.left:
                    q.append(n.left)
                if n.right:
                    q.append(n.right)
            out.append(level[::-1] if flip else level)
            flip = not flip
        return out
  5. 5

    Longest substring with at most K distinct characters.

    medium

    Slide a window with a count map. Expand right; while the map has more than K keys, shrink from the left, deleting keys that reach zero. Track the longest window. O(n). Mistake: not deleting zero-count keys, so the distinct count is wrong.

    python
    from collections import defaultdict
    
    def longest_k_distinct(s, k):
        cnt, left, best = defaultdict(int), 0, 0
        for right, ch in enumerate(s):
            cnt[ch] += 1
            while len(cnt) > k:
                cnt[s[left]] -= 1
                if cnt[s[left]] == 0:
                    del cnt[s[left]]
                left += 1
            best = max(best, right - left + 1)
        return best
  6. 6

    Generate all subsets of a list of distinct numbers.

    medium

    Backtrack: for each position decide to include or exclude the element, or iteratively extend every existing subset with the new element. There are 2 to the power n subsets, so O(n times 2^n). Mistake: appending the same list object instead of a copy, so later changes alter stored subsets.

    python
    def subsets(a):
        out = [[]]
        for x in a:
            out += [s + [x] for s in out]
        return out
    java
    static java.util.List<java.util.List<Integer>> subsets(int[] a) {
        java.util.List<java.util.List<Integer>> out = new java.util.ArrayList<>();
        out.add(new java.util.ArrayList<>());
        for (int x : a) {
            int size = out.size();
            for (int i = 0; i < size; i++) {
                java.util.List<Integer> s = new java.util.ArrayList<>(out.get(i));
                s.add(x);
                out.add(s);
            }
        }
        return out;
    }
  7. 7

    Validate a binary search tree.

    medium

    Recurse with an allowed open interval (low, high); each node must lie strictly inside, and children narrow the interval. O(n) time, O(h) space. Mistake: checking only that each node is greater than its left child and less than its right child, which misses violations deeper in a subtree.

    python
    def is_bst(node, lo=float('-inf'), hi=float('inf')):
        if node is None:
            return True
        if not (lo < node.val < hi):
            return False
        return is_bst(node.left, lo, node.val) and is_bst(node.right, node.val, hi)
  8. 8

    Search a target in a row-wise and column-wise sorted matrix.

    medium

    Start at the top-right corner. If the value equals the target, done; if larger, move left; if smaller, move down. Each step discards a row or column: O(m + n). Mistake: binary searching each row when the staircase is simpler and faster.

    python
    def search_matrix(m, target):
        if not m:
            return False
        r, c = 0, len(m[0]) - 1
        while r < len(m) and c >= 0:
            if m[r][c] == target:
                return True
            if m[r][c] > target:
                c -= 1
            else:
                r += 1
        return False
  9. 9

    Find all start indices of anagrams of a pattern in a string.

    medium

    Slide a window of the pattern's length with a count difference. Maintain counts of the window and compare with the pattern's counts, using a matching counter for O(n) or comparing 26-length arrays for O(26 n). Mistake: sorting each window, which is O(n m log m).

    python
    from collections import Counter
    
    def find_anagrams(s, p):
        need, win, out = Counter(p), Counter(), []
        for i, ch in enumerate(s):
            win[ch] += 1
            if i >= len(p):
                old = s[i - len(p)]
                win[old] -= 1
                if win[old] == 0:
                    del win[old]
            if win == need:
                out.append(i - len(p) + 1)
        return out
  10. 10

    Spiral order of a matrix.

    medium

    Keep four boundaries (top, bottom, left, right) and walk right, down, left and up, shrinking a boundary after each side, with checks that rows or columns remain before the left and up passes. O(mn). Mistake: omitting those checks, which duplicates elements for single-row or single-column matrices.

    python
    def spiral(m):
        out = []
        t, b, l, r = 0, len(m) - 1, 0, len(m[0]) - 1
        while t <= b and l <= r:
            out += m[t][l:r + 1]
            out += [m[i][r] for i in range(t + 1, b + 1)]
            if t < b:
                out += m[b][l:r][::-1]
            if l < r:
                out += [m[i][l] for i in range(b - 1, t, -1)]
            t, b, l, r = t + 1, b - 1, l + 1, r - 1
        return out
  11. 11

    Minimum time to finish tasks with dependencies (critical path).

    hard

    Topologically sort the tasks and keep, for each task, the earliest finish time: its own duration plus the maximum finish time of its prerequisites. The answer is the maximum finish time. O(V + E). Mistake: summing all durations, which ignores that independent tasks can run in parallel.

    python
    from collections import deque
    
    def min_project_time(durations, deps):
        n = len(durations)
        adj = [[] for _ in range(n)]
        indeg = [0] * n
        for a, b in deps:           # a must finish before b starts
            adj[a].append(b)
            indeg[b] += 1
        finish = durations[:]
        q = deque(i for i in range(n) if indeg[i] == 0)
        seen = 0
        while q:
            u = q.popleft()
            seen += 1
            for v in adj[u]:
                finish[v] = max(finish[v], finish[u] + durations[v])
                indeg[v] -= 1
                if indeg[v] == 0:
                    q.append(v)
        return max(finish) if seen == n else -1

Frequently asked questions

How many coding problems are in the ServiceNow test?

Reports describe two DSA questions with MCQs, but formats vary. Check your own invitation.

What difficulty should I prepare for?

Medium-level problems on arrays, strings, trees, graphs and backtracking. See how to crack the online assessment.

Does the test include SQL?

Some reports mention SQL and DBMS MCQs.

Where can I read the process?

See how to crack the ServiceNow interview.

Sources

Related guides

More in Company Interview Questions

See all in this section