Autocoder

UST coding round questions

Last updated 2026-11-19

UST works with healthcare, retail, banking and telecom clients on digital engineering projects, so a fresher's first exposure to the company's coding bar tends to be short programs over everyday business data. Reports from candidates describe an online assessment with aptitude and reasoning plus a programming part at easy to medium level. There is no UST syllabus we can quote, which means this page is practice in that spirit and nothing more.

Twelve problems follow, each written in Python first and Java second, with the reasoning, the cost and the mistake to avoid. They lean on arrays, matrices, hashing, stacks and a heap because those are the tools that turn up when the prompt describes patients, ledgers or payroll. For the spoken rounds, see UST interview questions.

Round style (commonly reported)Aptitude and reasoning plus a programming section
Practice difficultyEasy to medium
Code shownPython first, Java second

Reading a business story as a data problem

A prompt about hospital wards or payroll is a normal algorithm question wearing a costume. Strip the story to its inputs and the thing being asked: ages into groups, a grid searched for a value, intervals overlapping at the same moment. Writing that one-line translation at the top of your scratch area keeps you from solving a harder problem than the one set.

Constraints decide the approach. If a statement gives a few hundred records, a nested loop passes. If it gives a hundred thousand, you need a hash lookup, a sort or a heap. Look for that number before you pick a method.

The tools these twelve problems rely on

Hiring status

We have no sourced UST statement on fresher numbers, dates or eligibility, so none are given here. Your invitation email and UST's careers site hold the current test details.

UST coding round questions: questions with worked answers

  1. 1

    Given a list of patient ages, count how many fall in the bands 0-17, 18-59 and 60 or above.

    easy

    Bucket counting. Classify each age with two comparisons and increment a counter held in a map whose keys are created up front, so a band with zero patients still appears in the output. O(n) time, O(1) space. The usual slip is using inclusive upper bounds twice, which puts age 18 or 60 into two bands.

    python
    def age_bands(ages):
        out = {"0-17": 0, "18-59": 0, "60+": 0}
        for a in ages:
            key = "0-17" if a < 18 else "18-59" if a < 60 else "60+"
            out[key] += 1
        return out
    java
    import java.util.*;
    class Bands {
        static Map<String, Integer> ageBands(int[] ages) {
            Map<String, Integer> out = new LinkedHashMap<>();
            out.put("0-17", 0); out.put("18-59", 0); out.put("60+", 0);
            for (int a : ages) {
                String key = a < 18 ? "0-17" : a < 60 ? "18-59" : "60+";
                out.merge(key, 1, Integer::sum);
            }
            return out;
        }
    }
  2. 2

    A tax-style ID must be exactly five uppercase letters, four digits and one uppercase letter, such as ABCDE1234F. Write a validator without regular expressions.

    easy

    Positional character checks. Verify the length is ten, then test each segment with character-class checks. O(1) because the length is fixed. In Python, str.isdigit accepts non-ASCII digits, so also test isascii. In Java use Character.isUpperCase carefully, since it accepts accented capitals; compare against the range 'A' to 'Z' for strictness.

    python
    def valid_id(s):
        if len(s) != 10 or not s.isascii():
            return False
        return (s[:5].isalpha() and s[:5].isupper()
                and s[5:9].isdigit()
                and s[9].isalpha() and s[9].isupper())
    java
    class IdCheck {
        static boolean validId(String s) {
            if (s.length() != 10) return false;
            for (int i = 0; i < 10; i++) {
                char c = s.charAt(i);
                boolean letter = c >= 'A' && c <= 'Z';
                boolean digit = c >= '0' && c <= '9';
                if ((i < 5 || i == 9) ? !letter : !digit) return false;
            }
            return true;
        }
    }
  3. 3

    Generate the first n rows of Pascal's triangle, which a clinic uses in a dosage-schedule demo.

    easy

    Each interior entry is the sum of the two entries above it. Build row by row from the previous row, padding with ones at both ends. Total work is O(n^2), matching the output size. Mistakes are mostly off-by-one: row zero is just [1], and a row of length r has r - 1 interior entries to compute.

    python
    def pascal(n):
        rows = []
        for r in range(n):
            row = [1] * (r + 1)
            for j in range(1, r):
                row[j] = rows[r - 1][j - 1] + rows[r - 1][j]
            rows.append(row)
        return rows
    java
    import java.util.*;
    class Tri {
        static List<List<Integer>> pascal(int n) {
            List<List<Integer>> rows = new ArrayList<>();
            for (int r = 0; r < n; r++) {
                List<Integer> row = new ArrayList<>();
                for (int j = 0; j <= r; j++) {
                    if (j == 0 || j == r) row.add(1);
                    else row.add(rows.get(r - 1).get(j - 1) + rows.get(r - 1).get(j));
                }
                rows.add(row);
            }
            return rows;
        }
    }
  4. 4

    A square ledger grid holds amounts. Return the absolute difference between the sum of its main diagonal and the sum of its anti-diagonal.

    easy

    Matrix indexing. Element (i, i) lies on the main diagonal and (i, n - 1 - i) on the anti-diagonal. One loop gives O(n) time on an n by n grid, O(1) space. The centre cell of an odd-sized grid is counted in both sums, which is correct for this question because the difference cancels it.

    python
    def diagonal_gap(g):
        n = len(g)
        main = sum(g[i][i] for i in range(n))
        anti = sum(g[i][n - 1 - i] for i in range(n))
        return abs(main - anti)
    java
    class Grid {
        static int diagonalGap(int[][] g) {
            int n = g.length, main = 0, anti = 0;
            for (int i = 0; i < n; i++) {
                main += g[i][i];
                anti += g[i][n - 1 - i];
            }
            return Math.abs(main - anti);
        }
    }
  5. 5

    Every row and every column of a matrix of invoice totals is sorted ascending. Decide whether a given total is present.

    medium

    Staircase search. Start at the top-right corner. If the value is larger than the target, drop one column; if smaller, move down one row. Each step discards a row or column, so O(rows + cols) time and O(1) space, against O(rows x cols) for a scan. Starting at the top-left fails because both neighbours are larger, so you cannot decide which way to go.

    python
    def has_total(m, target):
        if not m or not m[0]:
            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
    java
    class Search {
        static boolean hasTotal(int[][] m, int target) {
            if (m.length == 0 || m[0].length == 0) return false;
            int r = 0, c = m[0].length - 1;
            while (r < m.length && c >= 0) {
                if (m[r][c] == target) return true;
                if (m[r][c] > target) c--;
                else r++;
            }
            return false;
        }
    }
  6. 6

    Remove duplicates from a sorted array of branch codes in place and return the new length of the unique prefix.

    easy

    Read and write pointers. Keep a write index for the next unique slot; scan with a read index and copy an element only when it differs from the last one written. O(n) time, O(1) space. Comparing against the neighbour at the read position instead of the last written value works for sorted input too, but starting the write index at 0 rather than 1 overwrites the first element.

    python
    def dedupe_sorted(a):
        if not a:
            return 0
        w = 1
        for r in range(1, len(a)):
            if a[r] != a[w - 1]:
                a[w] = a[r]
                w += 1
        return w
    java
    class Dedupe {
        static int dedupeSorted(int[] a) {
            if (a.length == 0) return 0;
            int w = 1;
            for (int r = 1; r < a.length; r++) {
                if (a[r] != a[w - 1]) a[w++] = a[r];
            }
            return w;
        }
    }
  7. 7

    Evaluate a postfix expression such as "3 4 + 2 *" that an invoice calculator produces. Operators are +, -, * and /, and division truncates towards zero.

    medium

    Operand stack. Push numbers; on an operator pop the right operand first, then the left, apply it and push the result. The answer is the single value left. O(n) time and O(n) space. Swapping the operand order breaks subtraction and division. In Python, floor division rounds towards minus infinity, so divide the absolute values and restore the sign to truncate toward zero.

    python
    def eval_postfix(expr):
        st = []
        for tok in expr.split():
            if tok in "+-*/" and len(tok) == 1:
                b, a = st.pop(), st.pop()
                if tok == "+": st.append(a + b)
                elif tok == "-": st.append(a - b)
                elif tok == "*": st.append(a * b)
                else:
                    q = abs(a) // abs(b)
                    st.append(q if (a < 0) == (b < 0) else -q)
            else:
                st.append(int(tok))
        return st[0]
    java
    import java.util.*;
    class Postfix {
        static int eval(String expr) {
            Deque<Integer> st = new ArrayDeque<>();
            for (String tok : expr.trim().split("\\s+")) {
                if (tok.length() == 1 && "+-*/".contains(tok)) {
                    int b = st.pop(), a = st.pop();
                    switch (tok.charAt(0)) {
                        case '+': st.push(a + b); break;
                        case '-': st.push(a - b); break;
                        case '*': st.push(a * b); break;
                        default: st.push(a / b);
                    }
                } else {
                    st.push(Integer.parseInt(tok));
                }
            }
            return st.pop();
        }
    }
  8. 8

    Return the index of the first character in a string that does not repeat anywhere else, or -1.

    easy

    Two passes with a frequency table. Count every character, then scan again and return the first index whose count is one. O(n) time, O(k) space for k distinct characters. Checking uniqueness with index() inside a loop is O(n^2). Remember that uppercase and lowercase are different characters unless the statement says to fold case.

    python
    from collections import Counter
    
    def first_unique(s):
        freq = Counter(s)
        for i, ch in enumerate(s):
            if freq[ch] == 1:
                return i
        return -1
    java
    import java.util.*;
    class Unique {
        static int firstUnique(String s) {
            Map<Character, Integer> freq = new HashMap<>();
            for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);
            for (int i = 0; i < s.length(); i++) {
                if (freq.get(s.charAt(i)) == 1) return i;
            }
            return -1;
        }
    }
  9. 9

    Patients are admitted and discharged at given [admit, discharge) times. What is the minimum number of beds needed so nobody waits?

    medium

    Sweep with a min-heap of discharge times. Sort stays by admit time. For each stay, if the earliest discharge is at or before the new admit time, reuse that bed by popping it; push the new discharge time. The heap size at the end is the answer. O(n log n) time, O(n) space. Using a strict comparison instead of less-or-equal wastes a bed when one patient leaves exactly as another arrives.

    python
    import heapq
    
    def min_beds(stays):
        heap = []
        for admit, out in sorted(stays):
            if heap and heap[0] <= admit:
                heapq.heapreplace(heap, out)
            else:
                heapq.heappush(heap, out)
        return len(heap)
    java
    import java.util.*;
    class Beds {
        static int minBeds(int[][] stays) {
            Arrays.sort(stays, (a, b) -> Integer.compare(a[0], b[0]));
            PriorityQueue<Integer> heap = new PriorityQueue<>();
            for (int[] s : stays) {
                if (!heap.isEmpty() && heap.peek() <= s[0]) heap.poll();
                heap.add(s[1]);
            }
            return heap.size();
        }
    }
  10. 10

    Sort employee records by department name ascending and, within a department, by salary descending.

    easy

    Composite sort key. In Python use a tuple key with the salary negated; in Java chain comparators with thenComparingInt. O(n log n). Sorting twice also works if the sort is stable: first by salary descending, then by department. Negating a salary in a key is fine for numbers but not for strings, so for descending text use reverse sorting passes.

    python
    def sort_staff(staff):
        # staff items are (department, salary, name)
        return sorted(staff, key=lambda e: (e[0], -e[1]))
    java
    import java.util.*;
    class Staff {
        static class Emp {
            String dept, name; int salary;
            Emp(String d, int s, String n) { dept = d; salary = s; name = n; }
        }
        static void sortStaff(List<Emp> list) {
            list.sort(Comparator.comparing((Emp e) -> e.dept)
                                .thenComparingInt(e -> -e.salary));
        }
    }
  11. 11

    List every Armstrong number in a closed range [lo, hi], where a number equals the sum of its digits each raised to the number of digits.

    easy

    Digit-power check. For each candidate convert it to digits, raise each to the digit count and compare the sum with the number. Cost is O((hi - lo) x d) for d digits. 153 qualifies as 1 + 125 + 27. Raising to a fixed power of three instead of the digit count is the common mistake and wrongly rejects numbers like 9474.

    python
    def armstrong_in(lo, hi):
        out = []
        for n in range(lo, hi + 1):
            ds = str(n)
            if sum(int(c) ** len(ds) for c in ds) == n:
                out.append(n)
        return out
    java
    import java.util.*;
    class Armstrong {
        static List<Integer> armstrongIn(int lo, int hi) {
            List<Integer> out = new ArrayList<>();
            for (int n = lo; n <= hi; n++) {
                int d = String.valueOf(n).length(), sum = 0, t = n;
                while (t > 0) {
                    sum += (int) Math.pow(t % 10, d);
                    t /= 10;
                }
                if (sum == n) out.add(n);
            }
            return out;
        }
    }
  12. 12

    From a list of words in a complaint log, return the second most frequent word. Break ties alphabetically and return None when fewer than two distinct words exist.

    medium

    Count, then order by count descending and word ascending, and take the entry at index one. O(n + m log m) for m distinct words. The tie rule must be applied inside the sort key, otherwise the answer depends on insertion order. Reading only the second item of a most_common call is wrong when counts tie, because the library does not sort ties alphabetically.

    python
    from collections import Counter
    
    def second_frequent(words):
        ranked = sorted(Counter(words).items(), key=lambda kv: (-kv[1], kv[0]))
        return ranked[1][0] if len(ranked) > 1 else None
    java
    import java.util.*;
    class Complaints {
        static String secondFrequent(List<String> words) {
            Map<String, Integer> cnt = new HashMap<>();
            for (String w : words) cnt.merge(w, 1, Integer::sum);
            List<Map.Entry<String, Integer>> es = new ArrayList<>(cnt.entrySet());
            es.sort((a, b) -> a.getValue().equals(b.getValue())
                    ? a.getKey().compareTo(b.getKey())
                    : b.getValue() - a.getValue());
            return es.size() > 1 ? es.get(1).getKey() : null;
        }
    }

Frequently asked questions

What does the UST programming section usually look like?

Reports describe short problems of easy to medium difficulty alongside aptitude and reasoning. The exact count, language list and timing are in your invitation, not on this page.

Do I need Java if I prefer Python?

Only if the assessment or your target project requires it. Both languages are shown here so you can pick one and read the other for comparison.

Which of these problems is the hardest?

The postfix evaluator and the bed-count heap need the most care, because of operand order and the tie rule when a discharge equals an admission time.

How long should each problem take?

Aim for under ten minutes on the easy ones and about fifteen on the medium ones, including testing a tiny input and an empty one.

Where do I find real current details on UST hiring?

On UST's own careers pages and in the email you receive. This guide does not carry any hiring numbers or dates.

Related guides

More in Company Interview Questions

See all in this section