Autocoder

HCLTech Coding Round Questions with Solutions

Last updated 2026-11-19

This page works through ten data-structure problems in the style an HCLTech technical test or interview could draw on, each with Python and Java solutions, complexity and the mistakes that cost marks.

Use it with HCLTech interview questions, and read how to crack the DSA coding round for approach.

LevelEasy to medium, one hard
LanguagesPython and Java shown
TopicsLinked lists, trees, binary search, arrays

What HCLTech coding practice should cover

HCLTech's own recruitment page does not describe question content, and prep sources describe an online test mixing aptitude with technical questions and some coding. The problems below therefore target the classic data-structure toolkit that such a test or a technical interview is likely to draw on: linked lists, binary search, trees, in-place array edits and voting algorithms. These are practice problems in the style of those topics, not a recorded paper.

Approach for linked list and tree problems

HCLTech Coding Round Questions with Solutions: questions with worked answers

  1. 1

    Reverse a singly linked list

    easy

    Walk the list keeping prev and curr; at each step save curr.next, point curr.next to prev, then advance both. Return prev as the new head. Complexity: O(n) time, O(1) space. Common mistakes: losing the rest of the list by overwriting next before saving it, and returning the old head.

    python
    class Node:
        def __init__(self, v, nxt=None): self.v, self.next = v, nxt
    def reverse(head):
        prev = None
        while head:
            head.next, prev, head = prev, head, head.next
        return prev
    h = reverse(Node(1, Node(2, Node(3))))
    print(h.v, h.next.v, h.next.next.v)  # 3 2 1
    java
    class Solution {
        static class Node { int v; Node next; Node(int v) { this.v = v; } }
        static Node reverse(Node head) {
            Node prev = null;
            while (head != null) {
                Node nxt = head.next;
                head.next = prev;
                prev = head;
                head = nxt;
            }
            return prev;
        }
    }
  2. 2

    Detect a cycle in a linked list

    medium

    Floyd's tortoise and hare: slow moves one step, fast two. If they meet there is a cycle; if fast reaches the end there is none. To find the cycle start, reset slow to the head and move both one step until they meet. Complexity: O(n) time, O(1) space. Common mistakes: checking only fast and not fast.next for null, and using a visited set when constant space is requested.

    python
    class Node:
        def __init__(self, v): self.v, self.next = v, None
    def has_cycle(head):
        slow = fast = head
        while fast and fast.next:
            slow, fast = slow.next, fast.next.next
            if slow is fast: return True
        return False
    a, b, c = Node(1), Node(2), Node(3)
    a.next, b.next, c.next = b, c, a
    print(has_cycle(a))  # True
    java
    class Solution {
        static class Node { int v; Node next; Node(int v) { this.v = v; } }
        static boolean hasCycle(Node head) {
            Node slow = head, fast = head;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
                if (slow == fast) return true;
            }
            return false;
        }
    }
  3. 3

    Group anagrams

    medium

    Use the sorted letters of each word as a dictionary key and collect words under it. For lowercase-only input a 26-count tuple is a linear-time key. Complexity: O(n * k log k) time with sorting, O(n * k) space. Common mistakes: using the original word as the key and using a list as a dictionary key (unhashable in Python).

    python
    from collections import defaultdict
    def group(words):
        g = defaultdict(list)
        for w in words: g[''.join(sorted(w))].append(w)
        return list(g.values())
    print(group(["eat", "tea", "tan", "ate", "nat", "bat"]))
    java
    import java.util.*;
    class Solution {
        static List<List<String>> group(String[] words) {
            Map<String, List<String>> g = new HashMap<>();
            for (String w : words) {
                char[] c = w.toCharArray();
                Arrays.sort(c);
                g.computeIfAbsent(new String(c), k -> new ArrayList<>()).add(w);
            }
            return new ArrayList<>(g.values());
        }
    }
  4. 4

    First and last position of a target in a sorted array

    medium

    Run binary search twice: once to find the leftmost index with value at least target, and once for the rightmost. Verify the value matches before returning. Complexity: O(log n) time, O(1) space. Common mistakes: stopping at any match (returns an arbitrary duplicate) and infinite loops from wrong mid updates.

    python
    from bisect import bisect_left, bisect_right
    def search_range(a, t):
        l = bisect_left(a, t)
        if l == len(a) or a[l] != t: return [-1, -1]
        return [l, bisect_right(a, t) - 1]
    print(search_range([5, 7, 7, 8, 8, 10], 8))  # [3, 4]
    java
    class Solution {
        static int bound(int[] a, int t, boolean upper) {
            int lo = 0, hi = a.length;
            while (lo < hi) {
                int mid = (lo + hi) >>> 1;
                if (a[mid] < t || (upper && a[mid] == t)) lo = mid + 1; else hi = mid;
            }
            return lo;
        }
        static int[] searchRange(int[] a, int t) {
            int l = bound(a, t, false);
            if (l == a.length || a[l] != t) return new int[]{-1, -1};
            return new int[]{l, bound(a, t, true) - 1};
        }
    }
  5. 5

    Find the duplicate in an array of n+1 numbers from 1..n

    medium

    Treat the array as a linked list where index i points to a[i]; the duplicate is the cycle entrance, found with Floyd's algorithm without modifying the array. A set is simpler but uses extra space. Complexity: O(n) time, O(1) space. Common mistakes: sorting (modifies input and costs O(n log n)) and starting the pointers at index 1 instead of 0.

    python
    def find_duplicate(a):
        slow = fast = a[0]
        while True:
            slow, fast = a[slow], a[a[fast]]
            if slow == fast: break
        slow = a[0]
        while slow != fast:
            slow, fast = a[slow], a[fast]
        return slow
    print(find_duplicate([1, 3, 4, 2, 2]))  # 2
    java
    class Solution {
        static int findDuplicate(int[] a) {
            int slow = a[0], fast = a[0];
            do { slow = a[slow]; fast = a[a[fast]]; } while (slow != fast);
            slow = a[0];
            while (slow != fast) { slow = a[slow]; fast = a[fast]; }
            return slow;
        }
    }
  6. 6

    Move all zeros to the end, keeping order

    easy

    Keep a write index; copy each non-zero value to it, then fill the rest with zeros. One pass over the data, in place. Complexity: O(n) time, O(1) space. Common mistakes: building a new list when in-place is required and swapping so many times it becomes O(n squared) on shifts.

    python
    def move_zeros(a):
        w = 0
        for x in a:
            if x != 0:
                a[w] = x; w += 1
        for i in range(w, len(a)): a[i] = 0
        return a
    print(move_zeros([0, 1, 0, 3, 12]))  # [1, 3, 12, 0, 0]
    java
    class Solution {
        static void moveZeros(int[] a) {
            int w = 0;
            for (int x : a) if (x != 0) a[w++] = x;
            while (w < a.length) a[w++] = 0;
        }
    }
  7. 7

    Level-order traversal of a binary tree

    medium

    Breadth-first search with a queue. Process one level at a time by taking the queue length at the start of each level. Complexity: O(n) time, O(width) space. Common mistakes: mixing levels together by not fixing the level size before the inner loop, and not handling an empty tree.

    python
    from collections import deque
    class T:
        def __init__(self, v, l=None, r=None): self.v, self.l, self.r = v, l, r
    def levels(root):
        out, q = [], deque([root] if root else [])
        while q:
            out.append([])
            for _ in range(len(q)):
                n = q.popleft(); out[-1].append(n.v)
                if n.l: q.append(n.l)
                if n.r: q.append(n.r)
        return out
    print(levels(T(3, T(9), T(20, T(15), T(7)))))  # [[3], [9, 20], [15, 7]]
    java
    import java.util.*;
    class Solution {
        static class T { int v; T l, r; T(int v) { this.v = v; } }
        static List<List<Integer>> levels(T root) {
            List<List<Integer>> out = new ArrayList<>();
            if (root == null) return out;
            Queue<T> q = new LinkedList<>();
            q.add(root);
            while (!q.isEmpty()) {
                List<Integer> lvl = new ArrayList<>();
                for (int i = q.size(); i > 0; i--) {
                    T n = q.poll();
                    lvl.add(n.v);
                    if (n.l != null) q.add(n.l);
                    if (n.r != null) q.add(n.r);
                }
                out.add(lvl);
            }
            return out;
        }
    }
  8. 8

    Validate a binary search tree

    hard

    Pass allowed bounds down: every node must lie strictly between a lower and an upper bound inherited from its ancestors. Checking only a node against its immediate children is wrong. Complexity: O(n) time, O(h) space. Common mistakes: comparing only parent and child (misses a left-subtree node larger than the root) and using int bounds that equal valid node values.

    python
    class T:
        def __init__(self, v, l=None, r=None): self.v, self.l, self.r = v, l, r
    def is_bst(n, lo=float('-inf'), hi=float('inf')):
        if not n: return True
        if not (lo < n.v < hi): return False
        return is_bst(n.l, lo, n.v) and is_bst(n.r, n.v, hi)
    print(is_bst(T(5, T(1), T(7, T(6), T(8)))), is_bst(T(5, T(1), T(4, T(3), T(6)))))  # True False
    java
    class Solution {
        static class T { int v; T l, r; T(int v) { this.v = v; } }
        static boolean isBst(T n, long lo, long hi) {
            if (n == null) return true;
            if (n.v <= lo || n.v >= hi) return false;
            return isBst(n.l, lo, n.v) && isBst(n.r, n.v, hi);
        }
        static boolean isBst(T root) { return isBst(root, Long.MIN_VALUE, Long.MAX_VALUE); }
    }
  9. 9

    Best time to buy and sell a stock once

    easy

    Track the minimum price so far and the best profit if you sold today. Return 0 if prices only fall. Complexity: O(n) time, O(1) space. Common mistakes: selling before buying (using the global max and global min independently) and returning a negative profit.

    python
    def max_profit(p):
        lo, best = float('inf'), 0
        for x in p:
            lo = min(lo, x)
            best = max(best, x - lo)
        return best
    print(max_profit([7, 1, 5, 3, 6, 4]))  # 5
    java
    class Solution {
        static int maxProfit(int[] p) {
            int lo = Integer.MAX_VALUE, best = 0;
            for (int x : p) {
                lo = Math.min(lo, x);
                best = Math.max(best, x - lo);
            }
            return best;
        }
    }
  10. 10

    Majority element (appears more than n/2 times)

    medium

    Boyer-Moore voting: keep a candidate and a counter; matching elements increment, different ones decrement, and a zero counter picks a new candidate. If a majority exists it survives. Verify with a second pass when existence is not guaranteed. Complexity: O(n) time, O(1) space. Common mistakes: skipping the verification pass when the problem does not guarantee a majority, and sorting for O(n log n).

    python
    def majority(a):
        cand = cnt = 0
        for x in a:
            if cnt == 0: cand = x
            cnt += 1 if x == cand else -1
        return cand if a.count(cand) > len(a) // 2 else None
    print(majority([2, 2, 1, 1, 1, 2, 2]))  # 2
    java
    class Solution {
        static int majority(int[] a) {
            int cand = 0, cnt = 0;
            for (int x : a) {
                if (cnt == 0) cand = x;
                cnt += (x == cand) ? 1 : -1;
            }
            int c = 0;
            for (int x : a) if (x == cand) c++;
            return c > a.length / 2 ? cand : -1;
        }
    }

Frequently asked questions

Does HCLTech test linked lists and trees?

Prep material for technical interviews commonly includes them; HCLTech does not publish its question content.

Which language should I use?

Python or Java are both fine. Use the one you can trace by hand.

How hard is the HCLTech coding test?

Commonly reported as moderate; difficulty depends on the role and cycle.

What if I cannot solve a problem fully?

Submit a correct simpler version first. Partial test cases can still earn marks.

Sources

Related guides

More in Company Interview Questions

See all in this section