Capgemini Coding Interview Questions with Solutions | Updated 2026

Capgemini Coding Interview Questions with Solutions

Capgemini Coding Interview Questions with Solutions Article

About author

Sandip Kumar (Full Stack Developer )

Sandip Kumar is a skilled Full Stack Developer with expertise in developing scalable and robust web applications. He possesses strong proficiency in front-end and back-end technologies, along with excellent problem-solving and analytical skills. With a keen eye for detail and a collaborative approach, he is committed to delivering high-quality solutions while continuously learning and staying updated with the latest industry trends.

Last updated on 10th Aug 2026| 7580

23029 Ratings

Capgemini Coding Interview Questions With Solutions help candidates prepare for programming rounds conducted during Capgemini recruitment and technical interviews. These questions generally focus on basic programming, logical thinking, problem-solving, mathematical algorithms, strings, arrays, loops, and number-based problems. Freshers may encounter coding challenges that test the ability to understand a problem, develop an efficient approach, and produce correct output. Common topics include counting problems, age problems, percentages, profit and loss, number patterns, prime numbers, factorials, palindrome checks, and simple mathematical algorithms. Practicing these problems helps improve coding accuracy, logical reasoning, and confidence during timed assessments. The solutions can be implemented in languages such as Python, Java, C, or C++, depending on the candidate’s preferred programming language.

1. What Is A Variable In Programming?

Ans:

A variable is a named memory location used to store data in a program. The value stored in a variable can usually be changed during program execution based on the requirements of the program. Variables have a data type that determines what kind of value they can hold, such as numbers, characters, or Boolean values. Common variable types include integer, floating-point, character, and Boolean. Variables make programs easier to read, understand, modify, and maintain. For example, int age = 25 stores the integer value 25 in the variable age.

2. What Is A Data Type?

Ans:

A data type defines the type of value that a variable can store in a program. Common data types include integer, float, double, character, and Boolean, depending on the programming language. Data types help the compiler determine how much memory is required to store a particular value. They also determine which operations can be performed on the stored data. Choosing the correct data type improves memory usage, program performance, and reliability. For example, int is commonly used to store whole numbers such as 10, 25, or 100.

3. How To Check Whether A Number Is A Prime Number?

Ans:

  • num = 17
  • if num < 2:
  • print(“Not Prime”)
  • else:
  • for i in range(2, int(num ** 0.5) + 1):
  • if num % i == 0:
  • print(“Not Prime”)
  • break
  • else:
  • print(“Prime”)

4. How To Check Whether A Number Is A Palindrome?

Ans:

  • num = 121
  • reverse = int(str(num)[::-1])
  • if num == reverse:
  • print(“Palindrome”)
  • else:
  • print(“Not Palindrome”)

5. How To Check Whether A Number Is An Armstrong Number?

Ans:

  • num = 153
  • digits = str(num)
  • power = len(digits)
  • total = sum(int(digit) ** power for digit in digits)
  • if total == num:
  • print(“Armstrong Number”)
  • else:
  • print(“Not Armstrong Number”)

6. How To Check Whether A Number Is A Perfect Number?

Ans:

  • num = 28
  • total = 0
  • for i in range(1, num):
  • if num % i == 0:
  • total += i
  • if total == num:
  • print(“Perfect Number”)
  • else:
  • print(“Not Perfect Number”)

7. How To Check Whether A Number Is A Strong Number?

Ans:

  • num = 145
  • total = 0
  • for digit in str(num):
  • factorial = 1
  • for i in range(1, int(digit) + 1):
  • factorial *= i
  • total += factorial
  • if total == num:
  • print(“Strong Number”)
  • else:
  • print(“Not Strong Number”)

8. How To Find The Factorial Of A Number?

Ans:

  • num = 5
  • factorial = 1
  • for i in range(1, num + 1):
  • factorial *= i
  • print(“Factorial =”, factorial)

9. How To Generate The Fibonacci Series?

Ans:

  • n = 10
  • a = 0
  • b = 1
  • for i in range(n):
  • print(a, end=” “)
  • a, b = b, a + b

10. What Are Input And Output Operations?

Ans:

Input And Output Operations Are Used To Receive Data From The User And Display Results To The User. Input Operations Allow A Program To Accept Values Such As Numbers, Strings, Or Other Data From The Keyboard Or Another Source. Output Operations Display Processed Information, Messages, Or Results On The Screen. In Python, The input() Function Is Commonly Used To Accept User Input. The print() Function Is Used To Display Output. These Operations Are Fundamental Because They Allow Programs To Interact With Users And Process Required Data.

blogcourse-image

    Subscribe To Contact Course Advisor

    11. How Does Reverse A String?

    Ans:

    • text = “Capgemini”
    • reversed_text = text[::-1]
    • print(“Reversed String:”, reversed_text)

    12. How Does Check Whether A String Is A Palindrome?

    Ans:

    • text = “madam”
    • if text == text[::-1]:
    •    print(“Palindrome”)
    • else:
    •    print(“Not Palindrome”)

    13. How Does Count Vowels And Consonants In A String?

    Ans:

    • text = “capgemini”
    • vowels = 0
    • consonants = 0
    • for ch in text.lower():
    •    if ch.isalpha():
    •       if ch in “aeiou”:
    •          vowels += 1
    •       else:
    •          consonants += 1
    • print(“Vowels:”, vowels)
    • print(“Consonants:”, consonants)

    14. How Does Count Character Frequency In A String?

    Ans:

    • text = “programming”
    • frequency = {}
    • for ch in text:
    •    if ch in frequency:
    •       frequency[ch] += 1
    •    else:
    •       frequency[ch] = 1
    • print(frequency)

    15. How Does Remove Duplicate Characters From A String?

    Ans:

    • text = “programming”
    • result = “”
    • for ch in text:
    •    if ch not in result:
    •       result += ch
    • print(“String Without Duplicates:”, result)

    16. How Does Check Whether Two Strings Are Anagrams?

    Ans:

    • text1 = “listen”
    • text2 = “silent”
    • if sorted(text1) == sorted(text2):
    •    print(“Anagram”)
    • else:
    •    print(“Not Anagram”)

    17. How Does Find The First Non-Repeated Character?

    Ans:

    • text = “swiss”
    • for ch in text:
    •    if text.count(ch) == 1:
    •       print(“First Non-Repeated Character:”, ch)
    •       break

    18. How Does Count The Number Of Words In A String?

    Ans:

    • text = “Welcome To Capgemini”
    • words = text.split()
    • count = len(words)
    • print(“Number Of Words:”, count)

    19. How Does Reverse Words In A String?

    Ans:

    • text = “I Love Coding”
    • words = text.split()
    • reversed_words = words[::-1]
    • result = ” “.join(reversed_words)
    • print(“Reversed Words:”, result)

    20. How Does Check Whether A String Contains Only Digits?

    Ans:

    • text = “123456”
    • if text.isdigit():
    •    print(“Contains Only Digits”)
    • else:
    •    print(“Contains Non-Digit Characters”)

    21. How Does Find The Maximum And Minimum Elements In An Array?

    Ans:

    • numbers = [10, 25, 5, 40, 15]
    • maximum = numbers[0]
    • minimum = numbers[0]
    • for number in numbers:
    • if number > maximum:
    • maximum = number
    • if number < minimum:
    • minimum = number
    • print(“Maximum:”, maximum)
    • print(“Minimum:”, minimum)

    22. How Does Find The Second-Largest Element In An Array?

    Ans:

    • numbers = [10, 25, 5, 40, 15]
    • largest = second = float(‘-inf’)
    • for number in numbers:
    • if number > largest:
    • second = largest
    • largest = number
    • elif number > second and number != largest:
    • second = number
    • print(“Second Largest:”, second)

    23. How Does Sort An Array?

    Ans:

    • numbers = [40, 10, 30, 20, 50]
    • for i in range(len(numbers)):
    • for j in range(i + 1, len(numbers)):
    • if numbers[i] > numbers[j]:
    • numbers[i], numbers[j] = numbers[j], numbers[i]
    • print(“Sorted Array:”, numbers)

    24. How Does Remove Duplicates From An Array?

    Ans:

    • numbers = [10, 20, 10, 30, 20, 40]
    • unique = []
    • for number in numbers:
    • if number not in unique:
    • unique.append(number)
    • print(“Array After Removing Duplicates:”, unique)

    25. How Does Find Duplicate Elements In An Array?

    Ans:

    • numbers = [10, 20, 10, 30, 20, 40]
    • duplicates = []
    • for number in numbers:
    • if numbers.count(number) > 1 and number not in duplicates:
    • duplicates.append(number)
    • print(“Duplicate Elements:”, duplicates)

    26. How Does Find Missing Numbers In An Array?

    Ans:

    • numbers = [1, 2, 4, 5, 6]
    • n = 6
    • total = n * (n + 1) // 2
    • array_sum = sum(numbers)
    • missing = total – array_sum
    • print(“Missing Number:”, missing)

    27. How Does Find Pairs With A Given Sum?

    Ans:

    • numbers = [2, 4, 3, 5, 7, 8]
    • target = 10
    • for i in range(len(numbers)):
    • for j in range(i + 1, len(numbers)):
    • if numbers[i] + numbers[j] == target:
    • print(numbers[i], numbers[j])

    28. How Does Rotate An Array?

    Ans:

    • numbers = [1, 2, 3, 4, 5]
    • k = 2
    • k = k % len(numbers)
    • rotated = numbers[-k:] + numbers[:-k]
    • print(“Rotated Array:”, rotated)

    29. How Does Merge Two Arrays?

    Ans:

    • array1 = [1, 2, 3]
    • array2 = [4, 5, 6]
    • merged = array1 + array2
    • print(“Merged Array:”, merged)

    30. How Does Find The Sum Of All Elements In An Array?

    Ans:

    • numbers = [10, 20, 30, 40, 50]
    • total = 0
    • for number in numbers:
    • total = total + number
    • print(“Sum:”, total)

    31. How Does Print A Number Pattern?

    Ans:

    • n = 5
    • for i in range(1, n + 1):
    •    for j in range(1, i + 1):
    •       print(j, end=” “)
    •    print()

    32. How Does Print A Pyramid Pattern

    Ans:

    • n = 5
    • for i in range(1, n + 1):
    •    spaces = ” ” * (n – i)
    •    stars = “* ” * i
    •    print(spaces + stars)

    33. How Does Print An Inverted Pyramid Pattern?

    Ans:

    • n = 5
    • for i in range(n, 0, -1):
    •    spaces = ” ” * (n – i)
    •    stars = “* ” * i
    •    print(spaces + stars)

    34. How Does Print A Diamond Pattern?

    Ans:

    • n = 5
    • for i in range(1, n + 1):
    •    print(” ” * (n – i) + “* ” * i)
    • for i in range(n – 1, 0, -1):
    •    print(” ” * (n – i) + “* ” * i)

    35. How Does Print A Character Pattern?

    Ans:

    • n = 5
    • for i in range(1, n + 1):
    •    for j in range(i):
    •       print(chr(65 + j), end=” “)
    •    print()

    36. How Does Find Factorial Using Recursion?

    Ans:

    • def factorial(n):
    •    if n == 0 or n == 1:
    •       return 1
    •    return n * factorial(n – 1)
    • n = 5
    • print(“Factorial:”, factorial(n))

    37. How Does Generate Fibonacci Series Using Recursion?

    Ans:

    • def fibonacci(n):
    •    if n <= 1:
    •       return n
    •    return fibonacci(n – 1) + fibonacci(n – 2)
    • n = 10
    • for i in range(n):
    •    print(fibonacci(i), end=” “)

    38. How Does Find The Sum Of Natural Numbers?

    Ans:

    • def sum_natural(n):
    •    if n == 0:
    •       return 0
    •    return n + sum_natural(n – 1)
    • n = 10
    • print(“Sum:”, sum_natural(n))

    39. How Does Reverse A String Using Recursion?

    Ans:

    • def reverse_string(text):
    •    if len(text) <= 1:
    •       return text
    •    return reverse_string(text[1:]) + text[0]
    • text = “Capgemini”
    • print(“Reversed String:”, reverse_string(text))

    40. How Does Calculate Power Using Recursion?

    Ans:

    • def power(base, exponent):
    •    if exponent == 0:
    •       return 1
    •    return base * power(base, exponent – 1)
    • base = 2
    • exponent = 5
    • print(“Power:”, power(base, exponent))

    41. How Does Traverse An Array?

    Ans:

    • numbers = [10, 20, 30, 40, 50]
    • for number in numbers:
    •    print(number, end=” “)

    42. How Does Find The Largest Element In An Array?

    Ans:

    • numbers = [10, 45, 23, 67, 12]
    • largest = numbers[0]
    • for number in numbers:
    •    if number > largest:
    •       largest = number
    • print(“Largest Element:”, largest)

    Course Curriculum

    Enroll in Java Certification Course and UPGRADE Your Skills

    Weekday / Weekend BatchesSee Batch Details

    43. How Does Reverse A Linked List?

    Ans:

    • class Node:
    •    def __init__(self, data):
    •       self.data = data
    •       self.next = None
    • head = Node(10)
    • head.next = Node(20)
    • head.next.next = Node(30)
    • previous = None
    • current = head
    • while current:
    •    next_node = current.next
    •    current.next = previous
    •    previous = current
    •    current = next_node
    • head = previous

    44. How Does Implement A Stack Using A List?

    Ans:

    • stack = []
    • stack.append(10)
    • stack.append(20)
    • stack.append(30)
    • print(“Stack:”, stack)
    • element = stack.pop()
    • print(“Popped Element:”, element)
    • print(“Stack After Pop:”, stack)

    45. How Does Implement A Queue Using A List?

    Ans:

    • queue = []
    • queue.append(10)
    • queue.append(20)
    • queue.append(30)
    • print(“Queue:”, queue)
    • element = queue.pop(0)
    • print(“Removed Element:”, element)
    • print(“Queue After Removal:”, queue)

    46. How Does Count Frequency Of Elements Using Hashing?

    Ans:

    • numbers = [1, 2, 2, 3, 3, 3, 4]
    • frequency = {}
    • for number in numbers:
    •    frequency[number] = frequency.get(number, 0) + 1
    • print(“Frequency:”, frequency)

    .

    47. How Does Insert A Node Into A Binary Tree?

    Ans:

    • class Node:
    •    def __init__(self, data):
    •       self.data = data
    •       self.left = None
    •       self.right = None
    • root = Node(10)
    • root.left = Node(5)
    • root.right = Node(15)
    • print(“Root:”, root.data)
    • print(“Left Child:”, root.left.data)
    • print(“Right Child:”, root.right.data)
    • from collections import deque
    • graph = {
    •    0: [1, 2],
    •    1: [0, 3],
    •    2: [0, 4],
    •    3: [1],
    •    4: [2]
    • }
    • visited = set()
    • queue = deque([0])
    • visited.add(0)
    • while queue:
    •    node = queue.popleft()
    •    print(node, end=” “)
    •    for neighbor in graph[node]:
    •       if neighbor not in visited:
    •          visited.add(neighbor)
    •          queue.append(neighbor)

    48. How Does Perform Breadth-First Search In A Graph?

    Ans:

    • from collections import deque
    • graph = {
    •    0: [1, 2],
    •    1: [0, 3],
    •    2: [0, 4],
    •    3: [1],
    •    4: [2]
    • }
    • visited = set()
    • queue = deque([0])
    • visited.add(0)
    • while queue:
    •    node = queue.popleft()
    •    print(node, end=” “)
    •    for neighbor in graph[node]:
    •       if neighbor not in visited:
    •          visited.add(neighbor)
    •          queue.append(neighbor)

    49. What Is A Class And Object?

    Ans:

    A class is a blueprint or template used to define the properties and behaviors of objects. It can contain variables, methods, constructors, and other members required to represent an entity. An object is an instance of a class created during program execution. Multiple objects can be created from the same class, with each object maintaining its own data. For example, a Car class can define properties such as color and model and methods such as start(). A particular car created from the Car class becomes an object.

    50. What Is Encapsulation?

    Ans:

    Encapsulation is an object-oriented programming concept that combines data and methods within a single class. It also helps restrict direct access to internal data by using access control mechanisms. Private variables can be accessed or modified through public methods such as getters and setters. This approach protects data from unwanted or incorrect modifications. Encapsulation improves security, maintainability, and code organization. For example, a bank account can keep its balance private and provide methods for deposit and withdrawal.

    Encapsulation Interview Question
    Encapsulation

    51. What Is Inheritance?

    Ans:

    Inheritance allows one class to acquire properties and methods from another class. The existing class is commonly called the parent or superclass, while the new class is called the child or subclass. Inheritance promotes code reuse and reduces duplicate implementation. A child class can also add new properties and methods or modify inherited behavior. For example, a Dog class can inherit common features from an Animal class. Inheritance is an important concept for creating relationships between related classes.

    52. What Is Polymorphism?

    Ans:

    Polymorphism means the ability of an object or method to take different forms. It allows the same method name or interface to perform different operations depending on the object or input. Method overriding is an example of runtime polymorphism, where a child class provides its own implementation of a parent method. Method overloading is commonly associated with compile-time polymorphism in languages that support it. Polymorphism improves flexibility and allows common interfaces to work with different implementations. For example, different animal classes can implement the same sound() method differently.

    53. What Is Abstraction?

    Ans:

    Abstraction is the process of hiding unnecessary implementation details and exposing only the essential functionality. It helps users interact with an object without needing to understand its internal working. Abstract classes and interfaces are commonly used to implement abstraction. For example, a user can call a withdraw() method without knowing how the banking system internally processes the transaction. Abstraction reduces complexity and improves code organization. It also allows implementation details to change without significantly affecting users of the functionality.

    54. What Is A Constructor?

    Ans:

    A constructor is a special method used to initialize an object when it is created. It is automatically called during object creation in languages such as Java and C++. Constructors can initialize instance variables with default or user-provided values. A class can have different forms of constructors depending on the programming language. In Python, the __init__() method is commonly used for object initialization. Constructors help ensure that objects begin with valid and meaningful data.

    55. What Is The Difference Between Method Overloading And Method Overriding?

    Ans:

    Feature Method Overloading Method Overriding
    Meaning Same method name with different parameters in the same class. Child class provides a different implementation of a parent class method.
    Parameters Parameters must differ in number, type, or order. Parameters generally remain the same.
    Purpose Provides multiple ways to perform a similar operation. Allows a child class to customize inherited behavior.

    56. What Is A SELECT Query In SQL?

    Ans:

    A SELECT query is used to retrieve data from one or more tables in a database. It allows specific columns or all columns to be selected based on the requirement. The SELECT keyword specifies the columns that need to be displayed. The FROM keyword identifies the table from which the data should be retrieved. Additional clauses such as WHERE, GROUP BY, and ORDER BY can be used with SELECT queries. SELECT queries are commonly used for reading and analyzing database information.

    57. What Is The Difference Between WHERE And HAVING?

    Ans:

    The WHERE clause is used to filter individual records before grouping or aggregation takes place. The HAVING clause is used to filter grouped results after aggregation. WHERE can be used with normal column conditions and does not normally work directly with aggregate results. HAVING is commonly used with aggregate functions such as COUNT, SUM, and AVG. For example, WHERE salary > 30000 filters employees before grouping. HAVING COUNT(*) > 5 filters groups containing more than five records.

    58. What Is GROUP BY In SQL?

    Ans:

    The GROUP BY clause is used to group rows that have the same values in one or more columns. It is commonly used with aggregate functions such as COUNT, SUM, AVG, MIN, and MAX. For example, employees can be grouped based on their department. An aggregate function can then calculate the number of employees in each department. GROUP BY is useful for generating summary reports and analyzing data. The grouped results can also be filtered using the HAVING clause.

    59. What Is ORDER BY In SQL?

    Ans:

    The ORDER BY clause is used to arrange query results in a specific order. By default, sorting is performed in ascending order using ASC. The DESC keyword can be used when descending order is required. Multiple columns can also be included in an ORDER BY clause. For example, employees can be sorted first by department and then by salary. ORDER BY is useful when results need to be displayed in a meaningful or ranked sequence.

    60. What Is A JOIN In SQL?

    Ans:

    A JOIN is used to combine data from two or more tables based on a related column. Common JOIN types include INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN. An INNER JOIN returns only records that have matching values in both tables. A LEFT JOIN returns all records from the left table and matching records from the right table. JOINs are widely used in relational databases to retrieve related information stored across multiple tables.

    Course Curriculum

    Learn Java Training with Advanced Concepts By Industry Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

    61. What Is An INNER JOIN?

    Ans:

    An INNER JOIN returns only the records that have matching values in both tables. It requires a common or related column between the tables. For example, an employee table can be joined with a department table using department ID. Employees whose department ID does not have a matching department record will not appear. INNER JOIN is useful when only matching records are required. It is one of the most frequently used JOIN types in SQL.

    62. What Is A Subquery In SQL?

    Ans:

    • A subquery is a query written inside another SQL query. It is commonly used when the result of one query is required as input for another query. 
    • A subquery can be placed inside clauses such as WHERE, FROM, or SELECT. For example, a subquery can find the average salary and the outer query can find employees earning more than that average. 
    • Subqueries help solve complex database problems in smaller logical steps. They can also be replaced by JOINs or common table expressions in suitable situations.

    63. What Are Aggregate Functions In SQL?

    Ans:

    Aggregate functions perform calculations on multiple rows and return a single result or grouped results. Common aggregate functions include COUNT, SUM, AVG, MIN, and MAX. COUNT calculates the number of records, while SUM calculates the total of numeric values. AVG calculates the average, and MIN and MAX find the smallest and largest values. Aggregate functions are frequently combined with GROUP BY. They are useful for generating summaries and reports from database tables.

    64. How Does Find Duplicate Records In SQL?

    Ans:

    Duplicate records can be identified by grouping records based on the columns that should be unique. The GROUP BY clause groups records having identical values. The COUNT() function can then determine how many times each combination occurs. The HAVING COUNT(*) > 1 condition returns only groups containing duplicates. For example, duplicate email addresses can be found by grouping records based on the email column. This technique is commonly used for checking data quality and identifying repeated records.

    65. How Does Find The Second-Highest Salary In SQL?

    Ans:

    The second-highest salary can be found using different SQL techniques. One common approach is to use a subquery that finds the maximum salary below the highest salary. Another approach uses DENSE_RANK() to rank salaries and select the records having rank two. DISTINCT may be required when multiple employees have the same salary. The query should also handle cases where duplicate salary values exist. This is a common SQL interview question because it tests sorting, filtering, subqueries, and ranking concepts.

    66. What Is Big O Notation?

    Ans:

    Big O notation is used to describe the time or space complexity of an algorithm. It explains how the resource requirements of an algorithm grow as the input size increases. Common complexities include O(1), O(log n), O(n), O(n log n), and O(n²). O(1) represents constant complexity, while O(n) represents linear growth with the input size. Big O mainly focuses on the growth rate and ignores constant factors and smaller terms. It is useful for comparing algorithms and selecting efficient solutions.

    67. What Are Best, Average, And Worst Cases?

    Ans:

    Best case represents the minimum amount of work an algorithm performs for a particular input. Average case represents the expected performance across typical or randomly distributed inputs. Worst case represents the maximum amount of work required for an input. For example, linear search has O(1) best-case complexity when the target is the first element. Its average and worst-case complexities are generally O(n). Understanding these cases helps evaluate an algorithm’s performance under different input conditions.

    68. What Is The Time Complexity Of Common Array Operations?

    Ans:

    Accessing an array element by index generally takes O(1) time because the memory location can be calculated directly. Searching for an unsorted element using linear search takes O(n) time. Inserting or deleting an element at the beginning or middle can take O(n) because other elements may need to be shifted. Adding an element at the end of a dynamic array is usually O(1) amortized. Traversing all elements requires O(n) time. Understanding these complexities helps select suitable data structures for different operations.

    69. What Is The Time Complexity Of Searching Algorithms?

    Ans:

    • Linear search examines elements one by one and has O(n) worst-case time complexity. Its best case is O(1) when the target is the first element. Binary search works on sorted data by repeatedly dividing the search range into two parts. 
    • Binary search has O(log n) worst-case time complexity. Hash-table lookup is generally O(1) on average but can degrade to O(n) in unfavorable collision scenarios. 
    • Choosing the appropriate search algorithm depends on data organization and whether the data is sorted.

    70. What Is The Time Complexity Of Sorting Algorithms?

    Ans:

    Bubble sort, selection sort, and insertion sort generally have O(n²) worst-case time complexity. Merge sort has O(n log n) time complexity in the best, average, and worst cases. Quick sort has an average complexity of O(n log n), while its worst case can be O(n²) with poor pivot selection. Efficient sorting is important when working with large datasets. The choice of sorting algorithm depends on factors such as input size, memory usage, stability, and data characteristics.

    Sorting Algorithms Interview Questions
    Sorting Algorithms

    71. How Can Inefficient Code Be Optimized?

    Ans:

    Inefficient code can be optimized by first identifying the part of the program responsible for excessive execution time or memory usage. Nested loops should be examined because unnecessary nested iterations can increase complexity significantly. Appropriate data structures such as hash maps or sets can replace repeated searches through arrays. Repeated calculations can be stored and reused instead of being recalculated. Algorithms with better complexity should be selected when possible, such as binary search instead of linear search for sorted data. Optimization should preserve correctness while improving performance and resource utilization.

    72. How Does Solve A Simple Counting Problem?

    Ans:

    • numbers = [10, 20, 30, 40, 50]
    • count = 0
    • for number in numbers:
    •    if number > 25:
    •       count += 1
    • print(“Count:”, count)

    73. How Does Solve An Age Calculation Problem?

    Ans:

    • present_age = 25
    • years = 5
    • future_age = present_age + years
    • print(“Age After”, years, “Years:”, future_age)

    74. How Does Calculate A Percentage?

    Ans:

    • marks_obtained = 450
    • total_marks = 500
    • percentage = (marks_obtained / total_marks) * 100
    • print(“Percentage:”, percentage)

    75. How Does Calculate Profit And Loss?

    Ans:

    • cost_price = 500
    • selling_price = 650
    • if selling_price > cost_price:
    •    profit = selling_price – cost_price
    •    print(“Profit:”, profit)
    • elif selling_price < cost_price:
    •    loss = cost_price – selling_price
    •    print(“Loss:”, loss)
    • else:
    •    print(“No Profit No Loss”)

    76. How Does Calculate The Profit Percentage?

    Ans:

    • cost_price = 500
    • selling_price = 600
    • profit = selling_price – cost_price
    • profit_percentage = (profit / cost_price) * 100
    • print(“Profit Percentage:”, profit_percentage)

    77. How Does Calculate The Loss Percentage?

    Ans:

    • cost_price = 800
    • selling_price = 600
    • loss = cost_price – selling_price
    • loss_percentage = (loss / cost_price) * 100
    • print(“Loss Percentage:”, loss_percentage)

    78. How Does Find The Sum Of Natural Numbers?

    Ans:

    • n = 10
    • total = 0
    • for i in range(1, n + 1):
    •    total += i
    • print(“Sum Of Natural Numbers:”, total)

    79. How Does Check Whether A Number Is Even Or Odd?

    Ans:

    • num = 28
    • if num % 2 == 0:
    •    print(“Even Number”)
    • else:
    •    print(“Odd Number”)

    80. How Does Find The Average Of Numbers?

    Ans:

    • numbers = [10, 20, 30, 40, 50]
    • total = sum(numbers)
    • count = len(numbers)
    • average = total / count
    • print(“Average:”, average)

    81. How Does Find The Greatest Of Three Numbers?

    Ans:

    • a = 25
    • b = 40
    • c = 30
    • greatest = max(a, b, c)
    • print(“Greatest Number:”, greatest)

    82. How Does Find The Smallest Of Three Numbers?

    Ans:

    • a = 25
    • b = 40
    • c = 15
    • smallest = min(a, b, c)
    • print(“Smallest Number:”, smallest)

    83. How Does Check Whether A Number Is Divisible By Another Number?

    Ans:

    • num = 50
    • divisor = 5
    • if num % divisor == 0:
    •    print(“Divisible”)
    • else:
    •    print(“Not Divisible”)

    84. How Does Calculate Simple Interest?

    Ans:

    • principal = 10000
    • rate = 5
    • time = 2
    • simple_interest = (principal * rate * time) / 100
    • print(“Simple Interest:”, simple_interest)

    85. How Does Calculate Compound Interest?

    Ans:

    • principal = 10000
    • rate = 5
    • time = 2
    • amount = principal * (1 + rate / 100) ** time
    • compound_interest = amount – principal
    • print(“Compound Interest:”, compound_interest)

    86. How Does Find The Factorial Of A Number?

    Ans:

    • num = 5
    • factorial = 1
    • for i in range(1, num + 1):
    •    factorial *= i
    • print(“Factorial:”, factorial)

    87. How Does Find The GCD Of Two Numbers?

    Ans:

    • a = 24
    • b = 36
    • while b != 0:
    •    a, b = b, a % b
    • print(“GCD:”, a)

    88. How Does Find The LCM Of Two Numbers?

    Ans:

    • a = 12
    • b = 18
    • x = a
    • y = b
    • while y != 0:
    •    x, y = y, x % y
    • gcd = x
    • lcm = (a * b) // gcd
    • print(“LCM:”, lcm)

    89. How Does Check Whether A Number Is A Perfect Number?

    Ans:

    • num = 28
    • total = 0
    • for i in range(1, num):
    •    if num % i == 0:
    •       total += i
    • if total == num:
    •    print(“Perfect Number”)
    • else:
    •    print(“Not Perfect Number”)

    90. How Does Solve A Basic Logical Puzzle Using Two Numbers?

    Ans:

    • a = 10
    • b = 20
    • if a > b:
    •    print(“A Is Greater”)
    • elif b > a:
    •    print(“B Is Greater”)
    • else:
    •    print(“Both Numbers Are Equal”)

    Upcoming Batches

    Name Date Details
    Capgemini

    31 - Aug - 2026

    (Weekdays) Weekdays Regular

    View Details
    Capgemini

    02 - Sep- 2026

    (Weekdays) Weekdays Regular

    View Details
    Capgemini

    05 - Sep - 2026

    (Weekends) Weekend Regular

    View Details
    Capgemini

    06 - Sep - 2026

    (Weekends) Weekend Fasttrack

    View Details