Fill your College Details

Summarise With AI
Back

DXC Coding Questions & Solutions in Python 2025

Summarise With Ai
23rd Aug 2025
7 min read

Offering technology solutions to different industries, DXC Technology is a global IT services company. DXC assesses candidates coding skills and problem solving abilities in their hiring process. DXC coding interview usually focusses on basics of computer science, algorithms, data structures, and problem-solving techniques. This article will help you get ready for DXC's coding interview rounds by highlighting key concepts and the best coding problems to solve.

Concepts for DXC Coding Questions

Before we proceed with particular coding problems, you need to be familiar with the fundamental concepts that can be used to test by DXC. Here are some major concepts that are regularly tested in coding interviews:

  • Data Structures: A solid knowledge of data structures such as arrays, linked lists, stacks, queues, trees, graphs, heaps, and hashmaps is essential.
  • Algorithms: Familiarity with algorithms like sorting (QuickSort, MergeSort), searching (Binary Search), dynamic programming, backtracking, and greedy algorithms will be helpful.
  • Time Complexity: Be ready to examine and optimize code for time complexity (Big O notation), as performance generally is essential.
  • Problem-Solving: You must use algorithms and data structures to solve real-world problems efficiently.
  • Recursion: Recursive problem-solving methods, e.g., solving problems using divide and conquer solutions, will also be popular.

🎯 Calculate your GPA instantly — No formulas needed!!

Top Coding Questions and Answers asked in DXC

Here are the coding questions and answers asked in DXC:

1. You are given an unsorted array of size n -1 containing unique elements ranging from 1 to n. Find the missing number from the array.

def find_missing_number(lst, n):
    total_sum = (n * (n + 1)) // 2
    lst_sum = sum(lst)
    return total_sum - lst_sum

# example
lst = [1, 4, 2, 5, 6]
n = 6
print(find_missing_number(lst, n))  # Output: 3

Explanation

  • The total sum of integers from 1 to n can be calculated by the formula: n * (n + 1) // 2.
  • We can find the missing number by subtracting the total number from the numbers in the array from this total sum.

Output

4

2. Create a function that takes a string as a parameter and then reverses the string without built-in Python functions.

def reverse_string(st):
    return st[::-1]

# Assumed example
st = "hello"
print(reverse_string(st))  # "olleh"

Explanation

  • We use Python's slicing method ([::-1]) to reverse the string.
  • s[::-1] is the sequence of all characters in s, retrieved in reverse order.

Output

ygolonhceT XCD

3. Given an array, find the length of the largest subarray with a zero sum.

def largest_subarray_with_zero_sum(arr):
    prefix_sum = {}
    max_len = 0
    curr_sum = 0
    
    for i, num in enumerate(arr):
        curr_sum += num
        
        if curr_sum == 0:
            max_len = i + 1
        elif curr_sum in prefix_sum:
            max_len = max(max_len, i - prefix_sum[curr_sum])
        else:
            prefix_sum[curr_sum] = i
    
    return max_len

# Example array:
arr = [1, -1, 3, -2, 2]
print(largest_subarray_with_zero_sum(arr))  # Output: 4

Explanation

  • This solution utilizes the prefix sum method to maintain the running sum of all elements until an index i.
  • We utilize a hash map to maintain every cumulative sum's first occurrence (prefix sum). This helps us find subarrays with a zero sum more effectively.
  • If we have a repeated prefix sum, the subarray sum between the two is zero.

Output

4

4. Write a function to check if a given string is a palindrome.

def is_palindrome(s):
    return s == s[::-1]

# Example usage:
s = "madam"
print(is_palindrome(s))  # Output: True

Explanation

  • A palindrome is a string that reads the same way forward and backward. We can test for this property by comparing the original string with its reverse.
  • We simply compare the string with its reverse by slicing.
  • The solution is highly efficient with an O(n) time complexity.

Output

True

5. Write a function to find the Kth largest element in an unsorted array.

import heapq

def kth_largest(arr, k):
    return heapq.nlargest(k, arr)[-1]

# Example usage:
arr = [12, 3, 5, 7, 19]
k = 2
print(kth_largest(arr, k))  # Output: 12

Explanation

  • We use Python's heapq.nlargest() to find the most significant Kth element. The function returns us the k most prominent elements, and the last is the Kth largest.
  • A heap-based solution is efficient for this problem as it does not include sorting the entire list.
  • The solution takes O(n log k) time, which is better than sorting the entire array.

Output

12

6. Write a program to merge two sorted arrays into a single sorted array.

def merge_sorted_arrays(arr1, arr2):
    result = []
    i = j = 0
    while i < len(arr1) and j < len(arr2):
        if arr1[i] < arr2[j]:
            result.append(arr1[i])
            i += 1
        else:
            result.append(arr2[j])
            j += 1
    result.extend(arr1[i:])
    result.extend(arr2[j:])
    return result

# Example usage:
arr1 = [1, 3, 5]
arr2 = [2, 4, 6]
print(merge_sorted_arrays(arr1, arr2))  # Output: [1, 2, 3, 4, 5, 6]

Explanation

  • We declare two pointers for each array to compare elements and construct the resultant merged array.
  • As both arrays are given to be already sorted, using this approach leads to the merged array being sorted as well without further steps of sorting.
  • The approach operates in O(n + m), where m and n are the dimensions of the two given input arrays.

Output

[1, 2, 3, 4, 5, 6]

7. Given an array of integers, find the element that appears more than once.

def find_duplicate(arr):
    seen = set()
    for num in arr:
        if num in seen:
            return num
        seen.add(num)

# Example usage:
arr = [1, 3, 4, 2, 2]
print(find_duplicate(arr))  # Output: 2

Explanation

  • We use a set to keep track of elements we've encountered so far. If a component is in the set, it's a duplicate.
  • The search for duplicates is O(n) since we only scan the array once.
  • The space complexity is O(n) because of the use of the set.

Output

2

8. Write a function to detect a cycle in a linked list.

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def has_cycle(head: ListNode) -> bool:
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            return True
    return False

# Test the function
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)

node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node2  # Creating a cycle

print(has_cycle(node1))  # True

Explanation

  • We use Floyd's Tortoise and Hare algorithm (slow and fast pointers).
  • The slow pointer takes one step, and the fast pointer takes two steps. Both will converge somewhere if there is a cycle.

Output

True

9. Check if a string is a palindrome.

def is_palindrome(s: str) -> bool:
    return s == s[::-1]

# Example:
input_string = "racecar"
print(is_palindrome(input_string))  # Output: True

Explanation

  • We are checking the string with the reversed string.
  • Time complexity is O(n), where n is the length of the string.
  • Space complexity is O(1) as we only compare the string without storing extra data.

Output

True

10. Find the length of the longest substring without repeating characters.

def length_of_longest_substring(s: str) -> int:
    char_set = set()
    left = result = 0
    for right in range(len(s)):
        while s[right] in char_set:
            char_set.remove(s[left])
            left += 1
        char_set.add(s[right])
        result = max(result, right - left + 1)
    return result

# Example:
input_string = "abcabcbb"
print(length_of_longest_substring(input_string))  # Output: 3

Explanation

  • Sliding window technique is applied to keep a record of the longest substring without repeating characters.
  • A set is utilized to store characters in the current window.
  • The time complexity of the algorithm is O(n), where n represents the size of the string.

Output 

3

11. Rotate an array by k steps.

def rotate(nums: list, k: int) -> None:
    k = k % len(nums)
    nums[:] = nums[-k:] + nums[:-k]

# Example:
nums = [1, 2, 3, 4, 5, 6, 7]
rotate(nums, 3)
print(nums)  # Output: [5, 6, 7, 1, 2, 3, 4]

Explanation

  • We perform the modulo operation (k % len(nums)) to handle scenarios when k is larger than the array size.
  • Array slicing is utilized to rotate the array efficiently.
  • The above solution is O(n), where n is the size of the array.

Output

[5, 6, 7, 1, 2, 3, 4]

12. Find the intersection of two arrays.

def intersection(nums1: list, nums2: list) -> list:
    return list(set(nums1) & set(nums2))

# Example:
nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
print(intersection(nums1, nums2))  # Output: [2]

Explanation

  • Intersection of two arrays is done by using the set intersection operator &.
  • The algorithm makes sure that unique elements are only selected for the intersection.
  • Time complexity is O(n + m), where n and m are the sizes of the arrays.

Output

[2]

13. Check if the given string of parentheses is valid.

def is_valid(s: str) -> bool:
    stack = []
    for char in s:
        if char in "({[":
            stack.append(char)
        elif char in ")}]":
            if not stack:
                return False
            if char == ")" and stack[-1] != "(":
                return False
            if char == "}" and stack[-1] != "{":
                return False
            if char == "]" and stack[-1] != "[":
                return False
            stack.pop()
    return not stack

# Example:
input_string = "()[]{}"
print(is_valid(input_string))  # Output: True

Explanation

  • We use a stack to store the opening parentheses.
  • We verify that we see a matching most recent opening parenthesis when we see a closing parenthesis.
  • Time complexity is O(n) where n represents the number of characters in the string.

Output

True

14. Implement binary search.

def binary_search(arr: list, target: int) -> int:
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = left + (right - left) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

# Example:
arr = [1, 2, 3, 4, 5, 6, 7]
print(binary_search(arr, 4))  # Output: 3

Explanation

  • The method looks up a target element in a sorted list.
  • It performs the binary search method by halving the list time and time again, decreasing the search range.
  • If the target equals the center element, return the index; otherwise, the search continues within the correct half of the list.
  • If the target is not attained, the function returns -1.

Output

3

15. Find two numbers in a list that sum up to a target.

def two_sum(nums: list, target: int) -> list:
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i

# Example:
nums = [2, 7, 11, 15]
target = 9
print(two_sum(nums, target))  # Output: [0, 1]

Explanation

  • The function employs a dictionary (seen) to hold numbers seen.
  • For every number, it finds the complement (target - num). If the complement is visible, it is a pair whose sum equals the target.
  • The indices of the two numbers whose sum is the target are returned.

Output

[0, 1]

16. Write a function to return the nth Fibonacci number.

def fibonacci(n: int) -> int:
    if n <= 1:
        return n
    a, b = 0, 1
    for _ in range(2, n + 1):
        a, b = b, a + b
    return b

# Example:
print(fibonacci(5))  # Output: 5

Explanation

  • The Fibonacci sequence begins with 0 and 1; every next number is the sum of the previous two.
  • The function uses an iterative method to find the Fibonacci number at index n.
  • It returns the nth Fibonacci number.

Output

5

17. Remove duplicates from a sorted array in-place.

def remove_duplicates(nums: list) -> int:
    if not nums:
        return 0
    index = 1
    for i in range(1, len(nums)):
        if nums[i] != nums[i - 1]:
            nums[index] = nums[i]
            index += 1
    return index

# Example:
nums = [1, 1, 2]
print(remove_duplicates(nums))  # Output: 2

Explanation

  • The algorithm traverses the sorted list in a loop and compares each member with the last one.
  • It then shifts any new duplicate-free element to its proper position (in-place).
  • The function returns the size of the resulting array without duplicates.

Output

2

18. Write a function to generate the nth term of the "Count and Say" sequence.

def count_and_say(n: int) -> str:
    result = "1"
    for _ in range(n - 1):
        temp = ""
        count, char = 1, result[0]
        for i in range(1, len(result)):
            if result[i] == char:
                count += 1
            else:
                temp += str(count) + char
                char = result[i]
                count = 1
        temp += str(count) + char
        result = temp
    return result

# Example:
print(count_and_say(4))  # Output: "1211"

Explanation

  • The "Count and Say" sequence produces terms by counting adjacent digits in the last term.
  • The function recursively builds each term by counting the times each digit occurs in the current term and building the next term.
  • The function returns the nth term in the sequence.

Output

"1211"

19. Check if a number is a power of two.

def is_power_of_two(n: int) -> bool:
    return n > 0 and (n & (n - 1)) == 0

# Example:
print(is_power_of_two(16))  # Output: True

Explanation

  • A number is a power of two if it has exactly one bit set in its binary representation.
  • The function verifies whether n is larger than 0 and whether n - 1 is 0 when n is 0.
  • This verification checks if n is a power of two.

Output

True

20. Check if two strings are anagrams.

def is_anagram(s: str, t: str) -> bool:
    return sorted(s) == sorted(t)

# Example:
print(is_anagram("anagram", "nagaram"))  # Output: True

Explanation

  • Two strings are anagrams when the two strings have the same characters in the same quantity.
  • The function checks sorted forms of the two strings.
  • If the sorted elements are the same, then the strings are anagrams.

Output

True

21. Find the element that appears only once in a list where every other element appears twice.

def single_number(nums: list) -> int:
    result = 0
    for num in nums:
        result ^= num
    return result

# Example:
print(single_number([4, 1, 2, 1, 2]))  # Output: 4

Explanation

  • The distinct element is obtained by using the XOR operation.
  • XORing the same number twice results in 0, and thus the duplicate elements are eliminated.
  • The result is the unique element.

Output

4

22. Find the longest palindromic substring.

def longest_palindrome(s: str) -> str:
    def expand_around_center(left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return s[left + 1:right]

    longest = ""
    for i in range(len(s)):
        odd_palindrome = expand_around_center(i, i)
        even_palindrome = expand_around_center(i, i + 1)
        longest = max(longest, odd_palindrome, even_palindrome, key=len)
    return longest

# Example:
print(longest_palindrome("babad"))  # Output: "bab"

Explanation

  • The function employs the "expand around center" technique to look for palindromes around each character (odd-length) and between characters (even-length).
  • It expands from all possible centers as long as the characters on either side are equal.
  • It returns the longest palindrome discovered.

Output

"bab"

23. Move all zeroes in an array to the end without changing the order of the non-zero elements.

def move_zeroes(nums: list) -> None:
    j = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[j], nums[i] = nums[i], nums[j]
            j += 1

# Example:
nums = [0, 1, 0, 3, 12]
move_zeroes(nums)
print(nums)  # Output: [1, 3, 12, 0, 0]

Explanation

  • The function passes through the array and places non-zero elements at the start.
  • It maintains a pointer j to where the next non-zero element should be placed.
  • During this pass, the zeroes would have been moved to the end of the array.

Output

[1, 3, 12, 0, 0]

24. Reverse the words in a string.

def reverse_words(s: str) -> str:
    return ' '.join(s.split()[::-1])

# Example:
print(reverse_words("the sky is blue"))  # Output: "blue is sky the"

Explanation

  • The function splits the string into words using split(), which trims leading/trailing spaces.
  • It reverses the list of words and then concatenates them into a single string.
  • The output is the same string with reversed words.

Output

"blue is sky the"

25. Check if a binary tree is symmetric.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def is_symmetric(root: TreeNode) -> bool:
    def is_mirror(t1, t2):
        if not t1 and not t2:
            return True
        if not t1 or not t2:
            return False
        return (t1.val == t2.val) and is_mirror(t1.left, t2.right) and is_mirror(t1.right, t2.left)

    return is_mirror(root, root)

# Example:
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right.left = TreeNode(4)
root.right.right = TreeNode(3)

print(is_symmetric(root))  # Output: True

Explanation

  • The function verifies whether a binary tree is a mirror tree by comparing left and right subtrees.
  • The helper function is_mirror, which is called recursively to check symmetry between corresponding subtrees.
  • The binary tree is symmetric if the left and right subtrees are mirrors of one another.

Output

True

Tips to Crack DXC Coding Questions

Here are the tips to solve DXC coding questions in the assessment round:

  • Read the problem carefully in its entirety before you begin coding. Ensure that you have all the edge cases.
  • Consider what data structure or algorithm would be ideal for the problem. If you have doubt, start with a brute-force approach and then optimize it.
  • Keep the time complexity and space complexity in mind while coding. Try to balance correctness with efficiency.
  • Practice coding regularly. Practice coding problems using websites like LeetCode, HackerRank, or CodeSignal and improve your problem-solving skills.
  • Write clean code that is maintainable and readable. Pay attention to variable names, proper indentation, and modularity.
  • Test your code at all times using edge cases such as empty inputs, extremely large numbers, or special cases which can ruin your solution.
  • If you're interviewing face-to-face or remotely, expect to be asked to describe your thought process in detail. Interviewers want to see your thinking around a problem even if your original solution isn't ideal.

Conclusion

In conclusion, the coding section in DXC interviews can be tricky, but if you are well-prepared, you will clear it. Concentrate on data structures, algorithms, and the study of time complexity analysis, and crack different types of coding problems by practicing them. The key factors are consistent approach, good thinking, and correct explanation of your thought processes.

Frequently Asked Questions

1. How should I prepare for the DXC coding interview? 

Practice coding questions on websites such as LeetCode, CodeForces, or HackerRank. Concentrate on data structures, algorithms, and time complexity analysis. Read about concepts such as recursion, dynamic programming, and graph algorithms.

2. Which programming languages do candidates prefer using for DXC coding questions? 

Candidates can mostly use Python, Java, C++, or C for coding assessments. Python is the most favored option since it is easy to work with and simple.

3. How challenging are the coding issues in DXC interviews?

DXC coding issues can be challenging, but you should be prepared to have questions that demand excellent problem-solving skills and a good grasp of algorithms and data structures. Practice consistently to hone your skills.

4. Which type of topics are covered in DXC coding interviews?

Arrays, linked lists, strings, trees, graphs, dynamic programming, sorting, searching algorithms, and time complexity analysis.

5. Can I use outside libraries during the coding interview?

Interviewers want you to do it yourself, so it is advisable not to use outside libraries. But there might be situations where you can use standard libraries for certain operations. Always request the interviewer.

Summarise With Ai

Read More Articles

Chat with us
Chat with us
Talk to career expert