Infosys Interview Preparation Guide

55+ interview questions with complete code solutions — technical, HR, aptitude, and coding rounds for freshers.

QuestionAnswerCategory
Q1. Write a program to reverse an array of integers.Use two-pointer technique: start from both ends, swap elements, and move pointers towards center.
def reverse_array(arr):
    start, end = 0, len(arr) - 1
    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1
    return arr

# Example usage
print(reverse_array([1, 2, 3, 4, 5]))  # Output: [5, 4, 3, 2, 1]
Coding
Q2. Check if a given string is a palindrome.Compare the string with its reverse. A palindrome reads the same forwards and backwards.
def is_palindrome(s):
    # Remove spaces and convert to lowercase
    s = s.replace(" ", "").lower()
    return s == s[::-1]

# Example usage
print(is_palindrome("racecar"))  # Output: True
print(is_palindrome("hello"))    # Output: False
Coding
Q3. Find the second largest number in an array.Use two variables to track first and second largest numbers.
def second_largest(arr):
    first = second = float('-inf')
    for n in arr:
        if n > first:
            second = first
            first = n
        elif n > second and n < first:
            second = n
    return second

# Example usage
print(second_largest([10, 20, 4, 45, 99]))  # Output: 45
Coding
Q4. Find all occurrences of a substring in a string.Iterate through the string and use find() method or startswith() to locate all positions.
def find_all_occurrences(text, pattern):
    positions = []
    start = 0
    while True:
        pos = text.find(pattern, start)
        if pos == -1:
            break
        positions.append(pos)
        start = pos + 1
    return positions

# Example usage
print(find_all_occurrences("abcabcabc", "abc"))  # Output: [0, 3, 6]
Coding
Q5. Check if two strings are anagrams of each other.Sort both strings and compare. Anagrams have same characters in different order.
def are_anagrams(s1, s2):
    return sorted(s1.replace(" ", "").lower()) == sorted(s2.replace(" ", "").lower())

# Example usage
print(are_anagrams("listen", "silent"))  # Output: True
print(are_anagrams("hello", "world"))    # Output: False
Coding
Q6. Remove duplicates from a sorted array.Use two pointers: one for unique elements, one for iteration.
def remove_duplicates(arr):
    if len(arr) == 0:
        return 0
    i = 0
    for j in range(1, len(arr)):
        if arr[i] != arr[j]:
            i += 1
            arr[i] = arr[j]
    return i + 1

# Example usage
arr = [1, 1, 2, 2, 3, 3, 4]
n = remove_duplicates(arr)
print(arr[:n])  # Output: [1, 2, 3, 4]
Coding
Q7. Rotate an array to the right by k steps.Use array slicing or reverse technique for optimal solution.
def rotate_array(arr, k):
    k = k % len(arr)
    return arr[-k:] + arr[:-k]

# Alternative approach (in-place)
def rotate_array_inplace(arr, k):
    def reverse(start, end):
        while start < end:
            arr[start], arr[end] = arr[end], arr[start]
            start += 1
            end -= 1
    k = k % len(arr)
    reverse(0, len(arr) - 1)
    reverse(0, k - 1)
    reverse(k, len(arr) - 1)

# Example usage
arr = [1, 2, 3, 4, 5]
print(rotate_array(arr, 2))  # Output: [4, 5, 1, 2, 3]
Coding
Q8. Find all pairs in an array that sum to a target value.Use hash map or two-pointer approach after sorting.
def find_pairs(arr, target):
    pairs = set()
    seen = set()
    for num in arr:
        complement = target - num
        if complement in seen:
            pairs.add((min(num, complement), max(num, complement)))
        seen.add(num)
    return list(pairs)

# Example usage
print(find_pairs([1, 5, 7, -1, 5], 6))  # Output: [(1, 5)]
Coding
Q9. Print first n Fibonacci numbers.Each Fibonacci number is sum of previous two numbers: F(n) = F(n-1) + F(n-2).
def fibonacci(n):
    fib_sequence = []
    a, b = 0, 1
    for _ in range(n):
        fib_sequence.append(a)
        a, b = b, a + b
    return fib_sequence

# Example usage
print(fibonacci(10))  # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Coding
Q10. Check if a number is an Armstrong number.An Armstrong number equals sum of its digits each raised to power of number of digits.
def is_armstrong(num):
    digits = [int(d) for d in str(num)]
    n = len(digits)
    return sum(d**n for d in digits) == num

# Example usage
print(is_armstrong(153))  # Output: True (1^3 + 5^3 + 3^3 = 153)
print(is_armstrong(9474)) # Output: True (9^4 + 4^4 + 7^4 + 4^4 = 9474)
Coding
Q11. Count frequency of each character in a string.Use dictionary/hash map to count character occurrences.
def count_char_frequency(s):
    char_count = {}
    for char in s:
        char_count[char] = char_count.get(char, 0) + 1
    return char_count

# Example usage
print(count_char_frequency("hello"))  # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
Coding
Q12. Find GCD (Greatest Common Divisor) of two numbers.Use Euclidean algorithm: GCD(a,b) = GCD(b, a mod b).
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

# Example usage
print(gcd(48, 18))  # Output: 6
Coding
Q13. Check if a number is prime.Check if number has any divisors other than 1 and itself.
def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    for i in range(3, int(n**0.5) + 1, 2):
        if n % i == 0:
            return False
    return True

# Example usage
print(is_prime(17))  # Output: True
print(is_prime(20))  # Output: False
Coding
Q14. Convert string to integer (atoi).Parse string digit by digit and build the integer.
def string_to_int(s):
    s = s.strip()
    if not s:
        return 0
    sign = -1 if s[0] == '-' else 1
    result = 0
    start = 1 if s[0] in ['-', '+'] else 0
    for i in range(start, len(s)):
        if not s[i].isdigit():
            break
        result = result * 10 + int(s[i])
    return sign * result

# Example usage
print(string_to_int("123"))    # Output: 123
print(string_to_int("-456"))   # Output: -456
Coding
Q15. Sort an array using bubble sort.Compare adjacent elements and swap if they are in wrong order. Repeat until sorted.
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

# Example usage
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))  # Output: [11, 12, 22, 25, 34, 64, 90]
Coding
Q16. Implement binary search on a sorted array.Divide search interval in half repeatedly until element is found or interval is empty.
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

# Example usage
print(binary_search([1, 3, 5, 7, 9, 11], 7))  # Output: 3
print(binary_search([1, 3, 5, 7, 9, 11], 6))  # Output: -1
Coding
Q17. Matrix addition of two 2D arrays.Add corresponding elements from both matrices.
def matrix_addition(matrix1, matrix2):
    result = []
    for i in range(len(matrix1)):
        row = []
        for j in range(len(matrix1[0])):
            row.append(matrix1[i][j] + matrix2[i][j])
        result.append(row)
    return result

# Example usage
m1 = [[1, 2], [3, 4]]
m2 = [[5, 6], [7, 8]]
print(matrix_addition(m1, m2))  # Output: [[6, 8], [10, 12]]
Coding
Q18. Calculate factorial of a number using recursion.Base case: factorial(0) = 1. Recursive case: factorial(n) = n * factorial(n-1).
def factorial(n):
    if n < 0:
        return -1  # Error case
    elif n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

# Example usage
print(factorial(5))  # Output: 120
Coding
Q19. Generate all prime numbers up to n using Sieve of Eratosthenes.Mark multiples of each prime as non-prime iteratively.
def sieve_of_eratosthenes(n):
    if n < 2:
        return []
    is_prime = [True] * (n + 1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(n**0.5) + 1):
        if is_prime[i]:
            for j in range(i*i, n + 1, i):
                is_prime[j] = False
    return [i for i in range(2, n + 1) if is_prime[i]]

# Example usage
print(sieve_of_eratosthenes(30))  # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Coding
Q20. Find common elements in two arrays.Use set intersection to find common elements efficiently.
def find_common_elements(arr1, arr2):
    return list(set(arr1) & set(arr2))

# Example usage
print(find_common_elements([1, 2, 3, 4], [3, 4, 5, 6]))  # Output: [3, 4]
Coding
Q21. What is the difference between an abstract class and an interface?Abstract classes can have both abstract and concrete methods with state (variables). Interfaces (until Java 8) only had abstract methods. Java 8+ allows default methods in interfaces.Technical
Q22. What is normalization in databases?Normalization is process of organizing data to reduce redundancy and improve data integrity. Normal forms: 1NF, 2NF, 3NF, BCNF.Technical
Q23. Explain polymorphism with example.Polymorphism: ability of object to take many forms. Method overloading (compile-time) and method overriding (runtime) are two types.Technical
Q24. What is the difference between equals() and == in Java?== compares object references. equals() compares object content/values. String class overrides equals().Technical
Q25. Explain the concept of garbage collection in Java.Automatic memory management: JVM automatically frees memory by removing unreferenced objects. Reduces memory leaks.Technical
Q26. What are ACID properties in databases?Atomicity: all or nothing. Consistency: valid state. Isolation: no interference. Durability: permanent after commit.Technical
Q27. What is the OSI model?Open Systems Interconnection model with 7 layers: Physical, Data Link, Network, Transport, Session, Presentation, Application.Technical
Q28. What is the difference between ArrayList and LinkedList?ArrayList: array-backed, fast random access, slower insertion/deletion. LinkedList: node-based, slower access, faster insertion/deletion.Technical
Q29. Explain JOIN operations in SQL.INNER JOIN: common records. LEFT JOIN: all from left table. RIGHT JOIN: all from right table. FULL JOIN: all records from both.Technical
Q30. What is exception handling in Java?Mechanism to handle runtime errors using try-catch-finally blocks. Allows graceful error handling without crashing program.Technical
Q31. Tell me about yourself.Start with education, highlight relevant projects/skills, mention internships, conclude with career goals. Keep it concise (2-3 minutes).HR
Q32. Why do you want to join Infosys?Mention company's reputation, growth opportunities, innovation focus, and alignment with your career goals.HR
Q33. What are your strengths?Highlight relevant strengths: problem-solving, teamwork, quick learner, adaptability, communication skills.HR
Q34. What are your weaknesses?Be honest but show improvement: "I take time to perfect details, but learned to prioritize for deadlines."HR
Q35. How do you handle pressure and deadlines?Share example: prioritize tasks, communicate with team, remain calm, focus on solutions.HR
Q36. Describe your teamwork experience.Use STAR method: Situation, Task, Action, Result. Emphasize collaboration and communication.HR
Q37. What are your salary expectations?Research industry standards. Give range: "Based on my skills and market research, I expect X to Y range."HR
Q38. Where do you see yourself in 5 years?Show ambition and growth: "Experienced developer with leadership skills, contributing to company growth."HR
Q39. Do you have any questions for us?Ask about team culture, growth opportunities, tech stack used, or company vision.HR
Q40. How do you stay updated with new technologies?Online courses, tech blogs, GitHub, coding platforms like LeetCode, attending webinars.HR
Q41. If a train travels 120 km in 2 hours, what is its average speed?Speed = Distance / Time = 120 / 2 = 60 km/h.Aptitude
Q42. Find the simple interest on 1000 at 5% per annum for 2 years.SI = (P × R × T) / 100 = (1000 × 5 × 2) / 100 = 100.Aptitude
Q43. What is 20% of 500?20% of 500 = (20/100) × 500 = 100.Aptitude
Q44. If A can do work in 10 days and B can do it in 15 days, how long will they take together?A's rate = 1/10, B's rate = 1/15. Combined rate = 1/10 + 1/15 = 5/30 = 1/6. Time = 6 days.Aptitude
Q45. Solve: 2x + 5 = 15.2x = 15 - 5 = 10. x = 5.Aptitude
Q46. What is the area of rectangle with length 5 and width 3?Area = Length × Width = 5 × 3 = 15 square units.Aptitude
Q47. Find compound interest on 5000 at 10% per annum for 2 years.A = P(1 + R/100)^T = 5000(1 + 10/100)^2 = 5000 × 1.21 = 6050. CI = 1050.Aptitude
Q48. If a book costs 200 and discount is 15%, what is final price?Discount = 15% of 200 = 30. Final price = 200 - 30 = 170.Aptitude
Q49. What is average of 10, 20, 30, 40?Average = (10 + 20 + 30 + 40) / 4 = 100 / 4 = 25.Aptitude
Q50. If ratio is 2:3 and sum is 50, find both numbers.Let numbers be 2x and 3x. 2x + 3x = 50. 5x = 50. x = 10. Numbers are 20 and 30.Aptitude
Q51. Write a program to find LCM of two numbers.LCM = (a × b) / GCD(a, b). Can also use mathematical approach.
def lcm(a, b):
    def gcd(x, y):
        while y:
            x, y = y, x % y
        return x
    return (a * b) // gcd(a, b)

# Example usage
print(lcm(12, 18))  # Output: 36
Coding
Q52. Reverse a linked list.Iterate through list, reverse pointers at each node.
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

def reverse_linked_list(head):
    prev = None
    current = head
    while current:
        next_temp = current.next
        current.next = prev
        prev = current
        current = next_temp
    return prev
Coding
Q53. Find middle element of linked list.Use slow and fast pointer approach. Slow moves 1 step, fast moves 2 steps.
def find_middle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
    return slow.data
Coding
Q54. Implement stack using array.Use array with push and pop operations.
class Stack:
    def __init__(self):
        self.items = []
    
    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        return self.items.pop() if not self.is_empty() else None
    
    def is_empty(self):
        return len(self.items) == 0
    
    def peek(self):
        return self.items[-1] if not self.is_empty() else None
Coding
Q55. Check if a string has balanced parentheses.Use stack: push opening brackets, pop on closing. Stack should be empty at end.
def is_balanced(s):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}
    for char in s:
        if char in mapping:
            if not stack or stack[-1] != mapping[char]:
                return False
            stack.pop()
        else:
            stack.append(char)
    return len(stack) == 0

# Example usage
print(is_balanced("({[]})"))  # Output: True
print(is_balanced("({[}])"))  # Output: False
Coding