Teradata interview questions & answers

8 real Teradata interview questions with full model answers — Coding. Drawn from the same verified bank ChannelPulse drills from (8 Teradata questions in total).

CodingMediumTeradataSoftware Engineer

1. Minimum Operations to Make Binary Palindrome (LeetCode)

Model answer

The task

For each number in an array, find the fewest +1 or -1 operations needed to reach a number whose binary representation reads the same in both directions. Return the answer for every array element.

Key idea

Because each operation changes the value by one, the answer is the distance to the nearest binary-palindrome value. Generate the possible binary palindromes once, sort them, then use binary search to check the nearest candidate on either side of each number.

Approach

  1. Find the largest bit length among the input numbers.
  2. For each bit length, enumerate prefixes with a leading 1 and mirror each prefix to form a palindrome of that length.
  3. Include 0, then sort and deduplicate the candidates.
  4. For each number, binary-search its insertion point among the candidates.
  5. Take the smaller distance to the candidate at that point or the one immediately before it.
from bisect import bisect_left
from typing import List

class Solution:
    def minOperations(self, nums: List[int]) -> List[int]:
        # Generate every binary palindrome up to one bit longer than
        # the largest input, so the candidate set covers nearby values.
        max_length = max((num.bit_length() for num in nums), default=0) + 1
        palindromes = {0}

        for length in range(1, max_length + 1):
            half_length = (length + 1) // 2
            first_prefix = 1 << (half_length - 1)
            end_prefix = 1 << half_length

            for prefix in range(first_prefix, end_prefix):
                left = bin(prefix)[2:]

                # For odd lengths, the middle bit must not be mirrored twice.
                mirrored_part = left[:-1] if length % 2 else left
                bits = left + mirrored_part[::-1]
                palindromes.add(int(bits, 2))

        ordered = sorted(palindromes)
        answers = []

        for num in nums:
            index = bisect_left(ordered, num)
            best = float("inf")

            if index < len(ordered):
                best = ordered[index] - num
            if index > 0:
                best = min(best, num - ordered[index - 1])

            answers.append(best)

        return answers

Complexity:

  • Time: O(P log P + n log P), where P is the number of generated palindromes and n is the array length.
  • Space: O(P), for storing the palindrome candidates.

Common follow-ups

  • Can the candidate set be reduced? Generate only palindromes near each number’s bit length, though this requires careful boundary handling.
  • What if operations have different costs in each direction? Compare the upward and downward candidate distances using their respective costs.
  • What if many queries arrive over time? Precompute and retain the sorted candidates, then answer each query with binary search.
CodingMediumTeradataSoftware Engineer

2. Count Pairs in Two Arrays (LeetCode)

Model answer

The task

Count index pairs (i, j) with i < j for which the sum of the two values from the first array is greater than the sum of the corresponding values from the second array.

Key idea

For each index, subtract its second-array value from its first-array value. A pair qualifies exactly when the two resulting differences sum to a positive number. Sorting these differences lets two pointers count qualifying pairs efficiently.

Approach

  1. Build a list of element-wise differences.
  2. Sort the list.
  3. Set pointers at both ends.
  4. If the pointed-to values sum to more than zero, every value between the pointers pairs successfully with the rightmost value; add that count and move the right pointer left.
  5. Otherwise, move the left pointer right.
from typing import List

class Solution:
    def countPairs(self, nums1: List[int], nums2: List[int]) -> int:
        differences = sorted(a - b for a, b in zip(nums1, nums2))

        left = 0
        right = len(differences) - 1
        count = 0

        while left < right:
            if differences[left] + differences[right] > 0:
                # Every index from left up to right - 1 forms a valid pair
                # with right, since the differences are sorted.
                count += right - left
                right -= 1
            else:
                left += 1

        return count

Complexity:

  • Time: O(n log n), due to sorting.
  • Space: O(n), for the differences list.

Common follow-ups

  • Can the sort be avoided? Not generally for arbitrary values; sorting enables the linear two-pointer scan.
  • What if the comparison is non-strict? For a condition allowing equal sums, change > 0 to >= 0.
  • How would you handle multiple queries over the same arrays? Precompute and sort the differences once, then reuse them where the query condition permits.
CodingMediumTeradataSoftware Engineer

3. Minimum Jumps to Reach End via Prime Teleportation (LeetCode)

Model answer

The task

Find the fewest moves from the first to the last array index. Each move can go to an adjacent index; if the current value is a prime p, it can also teleport to any index whose value is divisible by p.

Key idea

Treat indices as nodes in an unweighted graph and use BFS to find the shortest path. Group indices by the prime factors of their values, so a prime teleport can visit its divisible indices without checking the whole array.

Approach

  1. Build a smallest-prime-factor table up to the largest array value.
  2. For each index, add it to a bucket for each distinct prime factor of its value.
  3. Run BFS from index 0, exploring adjacent indices.
  4. When BFS reaches an index whose value is prime p, visit the indices in bucket p.
  5. Remove that bucket after processing: the first such index reached has the shortest distance, so later processing cannot improve the result.
from collections import defaultdict, deque
from typing import List

class Solution:
    def minJumps(self, nums: List[int]) -> int:
        n = len(nums)
        if n <= 1:
            return 0

        # Smallest prime factor for every value up to the maximum.
        limit = max(nums)
        spf = list(range(limit + 1))
        for p in range(2, int(limit**0.5) + 1):
            if spf[p] == p:
                for multiple in range(p * p, limit + 1, p):
                    if spf[multiple] == multiple:
                        spf[multiple] = p

        # For each prime p, store indices whose values are divisible by p.
        divisible_by = defaultdict(list)
        for i, value in enumerate(nums):
            x = value
            while x > 1:
                prime = spf[x]
                divisible_by[prime].append(i)
                while x % prime == 0:
                    x //= prime

        distance = [-1] * n
        distance[0] = 0
        queue = deque([0])

        while queue:
            i = queue.popleft()
            if i == n - 1:
                return distance[i]

            # Ordinary adjacent moves.
            for neighbor in (i - 1, i + 1):
                if 0 <= neighbor < n and distance[neighbor] == -1:
                    distance[neighbor] = distance[i] + 1
                    queue.append(neighbor)

            # A prime-valued position can teleport to its multiples.
            value = nums[i]
            if value >= 2 and spf[value] == value:
                for neighbor in divisible_by.pop(value, []):
                    if distance[neighbor] == -1:
                        distance[neighbor] = distance[i] + 1
                        queue.append(neighbor)

        return -1

Complexity:

  • Time: O(M log log M + n log M), where M is the largest value; this includes the sieve and factoring the values.
  • Space: O(M + n log M), for the sieve, BFS state, and prime-index buckets.

Common follow-ups

  • What if teleportation is allowed between values sharing any prime factor? Process every distinct prime-factor bucket for each visited index, only once per prime.
  • Can the sieve be avoided? Yes, factor values with trial division, which is practical only when values or their count are small.
  • Why is it safe to discard a bucket after processing? BFS reaches teleport sources in nondecreasing distance, so the first source processed gives every index in that bucket its shortest possible teleport distance.
CodingHardTeradataSoftware Engineer

4. Remove Boxes (LeetCode)

Model answer

The task

Given a row of colored boxes, repeatedly remove a contiguous group of one color. Each removal scores the square of the group’s size; maximize the total score.

Key idea

The best move may depend on boxes of the same color that can be joined after removing boxes between them. Use a memoized state (left, right, attached), where attached counts same-colored boxes carried just before left.

Approach

  1. Define a recursive function for an interval and its attached boxes.
  2. Combine any consecutive boxes matching the leftmost color into one group.
  3. Consider removing that group immediately.
  4. Also consider merging it with each later box of the same color, first removing the boxes in between.
  5. Memoize each state to avoid repeated work.
from functools import lru_cache
from typing import List

class Solution:
    def removeBoxes(self, boxes: List[int]) -> int:
        @lru_cache(None)
        def best(left: int, right: int, attached: int) -> int:
            if left > right:
                return 0

            # Fold adjacent boxes of the same color into the attached group.
            while left < right and boxes[left] == boxes[left + 1]:
                left += 1
                attached += 1

            group_size = attached + 1

            # Remove this group now.
            answer = group_size * group_size + best(left + 1, right, 0)

            # Or clear the interval between this box and a later match,
            # so the matching boxes can be removed together.
            for match in range(left + 1, right + 1):
                if boxes[match] == boxes[left]:
                    answer = max(
                        answer,
                        best(left + 1, match - 1, 0)
                        + best(match, right, attached + 1),
                    )

            return answer

        return best(0, len(boxes) - 1, 0)

Complexity:

  • Time: O(n⁴), with O(n³) possible memoized states and up to O(n) matches checked per state.
  • Space: O(n³) for the memoized states and recursion.

Common follow-ups

  • Why is attached needed? The value of removing a box group depends on same-colored boxes that may be joined to it later.
  • Can the memo be reduced to two dimensions? Not directly: the attached count changes the score and future merge options.
  • What if scoring is not the square of the group size? Replace the removal score calculation; the state structure still works when the score depends on group size.
CodingHardTeradataSoftware Engineer

5. Find the Sum of the Power of All Subsequences (LeetCode)

Model answer

The task

For every subsequence of nums, count the ways to choose a subsequence of it whose elements sum to k. Return the sum of those counts over all subsequences, modulo \(10^9+7\).

Key idea

Count pairs of nested subsequences directly: an outer subsequence and an inner subsequence with sum k. For each number, there are two choices that leave it out of the inner subsequence, and one choice that includes it and adds its value to the sum.

Approach

  1. Let dp[s] count valid choices across processed elements whose inner subsequence sums to s.
  2. Start with dp[0] = 1, representing the empty pair of subsequences.
  3. For each value, double each count to account for the two choices that do not add it to the inner sum.
  4. Add the previous count at s - value to account for including it in the inner subsequence.
  5. Return dp[k]. Handle zero separately so all transitions use counts from before processing it.
from typing import List

class Solution:
    def sumOfPower(self, nums: List[int], k: int) -> int:
        mod = 10**9 + 7
        dp = [0] * (k + 1)
        dp[0] = 1

        for value in nums:
            if value == 0:
                # The element can be absent from the outer subsequence,
                # present only in the outer subsequence, or in both.
                dp = [(3 * count) % mod for count in dp]
                continue

            # Descending order keeps dp[s - value] from the previous
            # set of processed elements.
            for total in range(k, -1, -1):
                ways = 2 * dp[total]
                if total >= value:
                    ways += dp[total - value]
                dp[total] = ways % mod

        return dp[k]

Complexity:

  • Time: O(nk), processing each sum for each number.
  • Space: O(k), storing counts for sums from 0 through k.

Common follow-ups

  • What if numbers can be negative? A fixed range from 0 to k is insufficient; track reachable sums with a map or offset-based DP.
  • Can the answer be computed without modulo? The same recurrence works, but counts may grow exponentially large.
  • What if we need the count for several target sums? Keep the full DP array and read each requested sum after processing all values.
CodingHardTeradataSoftware Engineer

6. Maximize the Minimum Powered City (LeetCode)

Model answer

The task

Given existing station counts along a line of cities, choose where to add up to k stations so that the least-powered city has as much power as possible. Each station contributes to cities within radius r.

Key idea

Binary-search the minimum power and greedily test whether it is achievable. When a city falls short, add exactly the deficit at the rightmost position that still covers it; this helps as many later cities as possible.

Approach

  1. Use prefix sums to calculate each city’s existing power.
  2. Binary-search between the current minimum power and that minimum plus k.
  3. For each candidate, scan cities left to right, tracking added power with a difference array.
  4. If a city is short, add the deficit greedily and record where that added power expires.
  5. Accept the candidate if the total added stations never exceeds k.
from typing import List

class Solution:
    def maxPower(self, stations: List[int], r: int, k: int) -> int:
        n = len(stations)

        # Prefix sums let us get the existing power of each city quickly.
        prefix = [0] * (n + 1)
        for i, count in enumerate(stations):
            prefix[i + 1] = prefix[i] + count

        power = []
        for i in range(n):
            left = max(0, i - r)
            right = min(n, i + r + 1)
            power.append(prefix[right] - prefix[left])

        def can_reach(target: int) -> bool:
            # Difference array tracks when greedily added power expires.
            changes = [0] * (n + 1)
            active_added = 0
            used = 0

            for i in range(n):
                active_added += changes[i]
                current = power[i] + active_added

                if current < target:
                    needed = target - current
                    used += needed
                    if used > k:
                        return False

                    # Place stations as far right as possible while covering i.
                    active_added += needed
                    expiry = min(n, i + 2 * r + 1)
                    changes[expiry] -= needed

            return True

        low = min(power)
        high = low + k

        while low < high:
            mid = (low + high + 1) // 2
            if can_reach(mid):
                low = mid
            else:
                high = mid - 1

        return low

Complexity:

  • Time: O(n log(k + 1)); each binary-search check scans the cities.
  • Space: O(n); prefix sums, powers, and the difference array.

Common follow-ups

  • What if stations have different costs? The greedy deficit step may no longer be optimal; the feasibility check needs to account for costs.
  • How would you handle cities arranged in a circle? Adapt the coverage windows to wrap around, taking care not to count a city twice.
  • Can the power calculations avoid prefix sums? Yes; a sliding window computes all existing powers in O(n) time with O(1) extra space beyond the result.
CodingHardTeradataSoftware Engineer

7. Minimum Cost to Hire K Workers (LeetCode)

Model answer

The task

Choose exactly k workers while paying each selected worker at least their minimum wage and keeping everyone’s pay proportional to their quality. Minimize the total pay.

Key idea

For a chosen group, the common pay-per-quality rate must be at least the largest minimum-wage-to-quality ratio in that group. Sort workers by this ratio; at each ratio, keep the k smallest qualities seen so far to minimize total cost at that rate.

Approach

  1. Pair each worker’s wage-to-quality ratio with their quality.
  2. Sort the pairs by ratio.
  3. Scan in order, maintaining a max-heap of the k smallest qualities seen so far.
  4. Once the heap contains k workers, calculate current_ratio * sum_of_qualities.
  5. Return the least cost found.
import heapq
from typing import List

class Solution:
    def mincostToHireWorkers(
        self, quality: List[int], wage: List[int], k: int
    ) -> float:
        workers = sorted(
            (w / q, q)
            for q, w in zip(quality, wage)
        )

        # Store negative qualities to simulate a max-heap.
        qualities_heap = []
        quality_sum = 0
        best_cost = float("inf")

        for ratio, q in workers:
            heapq.heappush(qualities_heap, -q)
            quality_sum += q

            if len(qualities_heap) > k:
                largest_q = -heapq.heappop(qualities_heap)
                quality_sum -= largest_q

            if len(qualities_heap) == k:
                best_cost = min(best_cost, ratio * quality_sum)

        return best_cost

Complexity:

  • Time: O(n log n), for sorting and heap operations.
  • Space: O(n), for the sorted worker list and heap.

Common follow-ups

  • What if more than k workers may be hired? Under the same pay rules, compare candidate groups of size k; extra workers only add cost.
  • How can floating-point error be reduced? Compare ratios using cross multiplication where possible, and use a suitable numeric type for the final cost.
  • What if each worker has a maximum acceptable wage too? The common rate must satisfy both lower and upper bounds for every selected worker; track whether a feasible shared rate exists.
CodingHardTeradataSoftware Engineer

8. Reducing Dishes (LeetCode)

Model answer

The task

Choose and order some dishes to maximize the sum of each chosen dish’s satisfaction multiplied by its position, where positions start at 1. The chosen order can be selected freely.

Key idea

For any chosen set, placing dishes in ascending satisfaction order maximizes the weighted sum. After sorting, consider adding dishes from highest satisfaction downward: each added dish increases the total by the sum of all selected satisfactions, so keep adding while that sum is positive.

Approach

  1. Sort satisfaction values in ascending order.
  2. Scan from the end, maintaining the sum of the dishes selected so far.
  3. When that sum is positive, add it to the answer; this is the gain from shifting the selected dishes one position later.
  4. Stop when the sum is no longer positive, since adding still lower values cannot make it positive again.
class Solution:
    def maxSatisfaction(self, satisfaction: list[int]) -> int:
        satisfaction.sort()

        running_sum = 0
        total = 0

        # Add the most satisfying remaining dish first.
        for value in reversed(satisfaction):
            running_sum += value
            if running_sum <= 0:
                break
            total += running_sum

        return total

Complexity:

  • Time: O(n log n), dominated by sorting.
  • Space: O(n) for Python’s sorting workspace.

Common follow-ups

  • What if dishes must be prepared in their original order? Use dynamic programming over choices and positions instead of sorting.
  • Can the result be negative? No; choosing no dishes gives a total of zero.
  • How would you return the chosen dishes too? Record the values included in the reverse scan, then reverse that list to get their serving order.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions