CrazyEngineers
  • TATA Consultancy Limited aka TCS conducts a 120 hour program for new recruits called TCS Xplore. I see lot of engineering candidates are looking for Python Coding Questions asked in TCS.

    I therefore decided to compile a few questions and answers that you can expect in TCS XPlore.

    I encourage fellow engineers to contribute to questions and answers so that we all can benefit. I'll set the ball rolling.

    Q1. Write a Python function that takes a list of integers and returns the maximum product of any three integers in the list.

    For example, if the input list is [-10, -10, 5, 2], the function should return 500 (which is the product of -10, -10, and 5).

    Note: The list can have both negative and positive integers.

    Answer -

    To solve this problem, we need to find the maximum product of any three integers in the given list. We can do this by iterating through the list and keeping track of the maximum product of any three integers seen so far.

    Algorithm:

    1. Sort the list in ascending order.
    2. Calculate the product of the last three elements in the sorted list.
    3. Calculate the product of the first two elements and the last element in the sorted list.
    4. Return the maximum of step 2 and step 3.

    Here's the Python code that implements the above algorithm:

    def max_product(nums):
        nums.sort()
        n = len(nums)
        return max(nums[0] * nums[1] * nums[n-1], nums[n-3] * nums[n-2] * nums[n-1])
    

    Let's break down the code and explain how it works:

    nums.sort() sorts the given list in ascending order. n = len(nums) stores the length of the list in a variable n. nums[0] * nums[1] * nums[n-1] calculates the product of the first two elements and the last element in the sorted list. nums[n-3] * nums[n-2] * nums[n-1] calculates the product of the last three elements in the sorted list. max() returns the maximum of the two products calculated in the previous steps.

    Running the tests with some sample inputs -

    print(max_product([-10, -10, 5, 2]))   # Output: 500
    print(max_product([-10, -10, -5, 2]))  # Output: 200
    print(max_product([1, 2, 3, 4, 5]))    # Output: 60
    

    In the first test case, the function correctly returns the maximum product of -10, -10, and 5, which is 500.

    In the second test case, the function returns the maximum product of -10, -10, and 2, which is 200.

    In the third test case, the function returns the maximum product of 3, 4, and 5, which is 60.

    I hope you find this useful. Will add more questions soon.

    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • Rohit Joshi

    Member1yr

    Q2. Write a Python function that takes a list of integers and returns the second largest number in the list. If there are no second largest numbers, the function should return None.

    For example, if the input list is [1, 2, 3, 4, 5], the function should return 4 (which is the second largest number in the list).

    Note: The list can have both negative and positive integers.

    Answer: -

    We need to find the second largest number in the given list.

    We can do this by iterating through the list and keeping track of the largest and second largest numbers seen so far.

    Algorithm:

    1. Initialise the largest and second largest variables to None.

    2. Iterate through the list and compare each number with the largest and second largest variables.

    3. If a number is greater than the largest variable, update the second largest variable to the value of the largest variable and update the largest variable to the current number.

    4. If a number is less than or equal to the largest variable but greater than the second largest variable, update the second largest variable to the current number.

    5. Return the value of the second largest variable.

    Sample Python Code -

    def second_largest(nums):
        largest = None
        second_largest = None
        for num in nums:
            if largest is None or num > largest:
                second_largest = largest
                largest = num
            elif second_largest is None or num > second_largest:
                second_largest = num
        return second_largest
    

    Let's break down the code and explain how it works:

    • largest and second_largest are initialised to None.
    • The for loop iterates through each number in the given list.
    • The first if statement checks if the current number is greater than the current largest number. If it is, the second largest number is updated to the value of the current largest number and the largest number is updated to the current number.
    • The second elif statement checks if the current number is less than or equal to the current largest number but greater than the current second largest number. If it is, the second largest number is updated to the current number.
    • The return statement returns the value of the second largest variable.

    Sample inputs and outputs -

    print(second_largest([1, 2, 3, 4, 5]))    # Output: 4
    print(second_largest([5, 4, 3, 2, 1]))    # Output: 4
    print(second_largest([1, 1, 2, 2, 3, 3]))  # Output: 2
    print(second_largest([1]))                # Output: None
    

    I hope you find this useful.

    Are you sure? This action cannot be undone.
    Cancel
  • Rohit Joshi

    Member1yr

    Q3. Given a list of integers, write a Python function find_largest_subarray_sum(arr) that finds the largest sum of a continuous subarray using the Divide and Conquer approach. The function should return the largest sum found.

    I've added comments to the code. Let me know if you do not understand any of it. The code is straightforward. Note - this is a difficult question. It's likely that you won't find questions of this difficulty in TCS XPlore.

    Pay attention to the logic.

    def find_largest_subarray_sum(arr):
        def cross_sum(arr, low, mid, high):
            # Initialize the sum of the left and right subarrays
            left_sum = float('-inf')
            right_sum = float('-inf')
    
            # Calculate the sum of the left subarray
            curr_sum = 0
            for i in range(mid, low - 1, -1):
                curr_sum += arr[i]
                if curr_sum > left_sum:
                    left_sum = curr_sum
    
            # Calculate the sum of the right subarray
            curr_sum = 0
            for i in range(mid + 1, high + 1):
                curr_sum += arr[i]
                if curr_sum > right_sum:
                    right_sum = curr_sum
    
            # Return the sum of the left and right subarrays
            return left_sum + right_sum
    
        def max_subarray_sum(arr, low, high):
            # Base case: if there's only one element, return the element
            if low == high:
                return arr[low]
    
            # Calculate the middle index
            mid = (low + high) // 2
    
            # Recursively find the largest sum in the left, right, and cross subarrays
            left_sum = max_subarray_sum(arr, low, mid)
            right_sum = max_subarray_sum(arr, mid + 1, high)
            cross_sum_ = cross_sum(arr, low, mid, high)
    
            # Return the largest sum among the three subarrays
            return max(left_sum, right_sum, cross_sum_)
    
        # Call the helper function with initial low and high indices
        return max_subarray_sum(arr, 0, len(arr) - 1)
    
    
    # Example usage
    arr = [2, -4, 5, -8, 7, -1, 3, -2]
    result = find_largest_subarray_sum(arr)
    print(f"The largest sum of a continuous subarray is: {result}")
    
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register