Flipkart Runway Coding Prep - Comprehensive Guide
Arrays
Explanation: An array is a collection of elements stored at contiguous memory locations.
Problem: Find the maximum sum subarray using Kadane's Algorithm.
def max_subarray_sum(arr):
max_sum = float('-inf')
current_sum = 0
for num in arr:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
# Example usage:
print(max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4])) # Output: 6
Problem: Rotate an array to the right by k positions.
def rotate_array(arr, k):
k %= len(arr)
return arr[-k:] + arr[:-k]
# Example usage:
print(rotate_array([1, 2, 3, 4, 5, 6, 7], 3)) # Output: [5,6,7,1,2,3,4]
Problem: Find the missing number in an array of n-1 elements.
def missing_number(arr, n):
expected_sum = n * (n + 1) // 2
actual_sum = sum(arr)
return expected_sum - actual_sum
# Example usage:
print(missing_number([1, 2, 4, 5, 6], 6)) # Output: 3
Strings
Explanation: A string is a sequence of characters. Common operations include searching,
concatenation, and transformation.
Problem: Check if a string is a palindrome.
def is_palindrome(s):
return s == s[::-1]
# Example usage:
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False
Problem: Find the longest common prefix among an array of strings.
def longest_common_prefix(strs):
if not strs:
return ""
prefix = strs[0]
for string in strs[1:]:
while not string.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
# Example usage:
print(longest_common_prefix(["flower","flow","flight"])) # Output: "fl"
Linked Lists
Explanation: A linked list is a linear data structure where elements (nodes) are connected using
pointers.
Problem: Reverse a linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverse_list(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
Recursion
Explanation: Recursion is a method of solving problems where a function calls itself.
Problem: Find the factorial of a number.
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
# Example usage:
print(factorial(5)) # Output: 120