[Go to site: main page, start]

0% found this document useful (0 votes)
73 views9 pages

Python Array DSA Solutions Guide

The document provides a comprehensive cheat sheet of important Array and String Data Structure and Algorithm (DSA) questions tailored for Data Engineering interviews, including Python code snippets, explanations, and time & space complexities. It covers various topics such as reversing arrays, finding maximum and minimum values, checking for palindromes, and more. Additionally, it offers to create a one-page PDF for quick revision before interviews.

Uploaded by

vipulzope143
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views9 pages

Python Array DSA Solutions Guide

The document provides a comprehensive cheat sheet of important Array and String Data Structure and Algorithm (DSA) questions tailored for Data Engineering interviews, including Python code snippets, explanations, and time & space complexities. It covers various topics such as reversing arrays, finding maximum and minimum values, checking for palindromes, and more. Additionally, it offers to create a one-page PDF for quick revision before interviews.

Uploaded by

vipulzope143
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Array DSA solutions Python

Got it ✅ — You want all important Array DSA questions for Data Engineering
interviews with Python shortcut code + simple explanation + Time & Space
Complexity.

Here’s your condensed cheat sheet for quick revision before the interview.

1. Reverse an Array
python

def reverse_array(arr):
return arr[::-1] # Python slicing

Explanation: Slicing with [::-1] reverses the array.


Time: O(n) | Space: O(n) (O(1) if done in-place with swapping).

2. Find Max and Min in Array


python

def min_max(arr):
return min(arr), max(arr) # Built-in functions

Explanation: Finds smallest and largest in one pass.


Time: O(n) | Space: O(1).

3. Find Second Largest Element


python

def second_largest(arr):
uniq = list(set(arr))

1/9
[Link](reverse=True)
return uniq[1] if len(uniq) > 1 else None

Explanation: Remove duplicates → sort → pick 2nd.


Time: O(n log n) | Space: O(n).
(Better O(n) version exists with one pass.)

4. Check if Array is Sorted


python

def is_sorted(arr):
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))

Time: O(n) | Space: O(1).

5. Rotate Array by K
python

def rotate(arr, k):


k %= len(arr)
return arr[-k:] + arr[:-k]

Time: O(n) | Space: O(n) (O(1) with in-place reversal).

6. Remove Duplicates (Sorted Array)


python

def remove_duplicates(arr):
res = []
for num in arr:
if not res or res[-1] != num:

2/9
[Link](num)
return res

Time: O(n) | Space: O(n).

7. Find Missing Number (1 to n)


python

def missing_number(arr):
n = len(arr) + 1
return n*(n+1)//2 - sum(arr)

Time: O(n) | Space: O(1).

8. Find All Pairs with Given Sum


python

def two_sum(arr, target):


seen = {}
for num in arr:
if target - num in seen:
return (target - num, num)
seen[num] = True

Time: O(n) | Space: O(n).

9. Kadane’s Algorithm (Max Subarray Sum)


python

def max_subarray_sum(arr):
max_sum = cur_sum = arr[0]
for num in arr[1:]:

3/9
cur_sum = max(num, cur_sum + num)
max_sum = max(max_sum, cur_sum)
return max_sum

Time: O(n) | Space: O(1).

10. Merge Two Sorted Arrays


python

def merge_sorted(a, b):


i=j=0
res = []
while i < len(a) and j < len(b):
if a[i] < b[j]:
[Link](a[i]); i += 1
else:
[Link](b[j]); j += 1
[Link](a[i:]); [Link](b[j:])
return res

Time: O(n+m) | Space: O(n+m).

11. Move Zeroes to End


python

def move_zeroes(arr):
pos = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[pos], arr[i] = arr[i], arr[pos]
pos += 1
return arr

Time: O(n) | Space: O(1).

4/9
12. Find Intersection of Two Arrays
python

def intersection(a, b):


return list(set(a) & set(b))

Time: O(n+m) | Space: O(min(n, m)).

If you want, I can prepare you a one-page PDF “DSA Arrays Quick Revision Sheet”
with all patterns, formulas, and tricky variations so you can revise in 5 minutes
before your interview.

Do you want me to make that PDF now?

Got it ✅ — You want all important String DSA questions for a Data Engineering
interview in Python shortcut form, with simple explanations and time & space
complexity.

Here’s your String DSA cheat sheet for quick revision.

1. Reverse a String
python

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

Explanation: Python slicing with step -1 reverses.


Time: O(n) | Space: O(n) (O(1) if in-place for char array).

5/9
2. Check Palindrome
python

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

Explanation: Compare string to its reverse.


Time: O(n) | Space: O(n).

3. Count Vowels and Consonants


python

def count_vowels(s):
vowels = "aeiouAEIOU"
v = sum(1 for ch in s if ch in vowels)
return v, len(s) - v

Time: O(n) | Space: O(1).

4. First Non-Repeating Character


python

from collections import Counter


def first_non_repeating(s):
count = Counter(s)
for ch in s:
if count[ch] == 1:
return ch

Time: O(n) | Space: O(n).

6/9
5. Anagram Check
python

def is_anagram(s1, s2):


return sorted(s1) == sorted(s2)

Time: O(n log n) | Space: O(n).


(Better: count characters → O(n) time.)

6. Remove All Duplicates


python

def remove_duplicates(s):
return "".join(sorted(set(s), key=[Link]))

Time: O(n) | Space: O(n).

7. Check if Rotation of Another


python

def is_rotation(s1, s2):


return len(s1) == len(s2) and s2 in (s1 + s1)

Time: O(n) | Space: O(n).

8. Longest Common Prefix


python

def longest_common_prefix(strs):
prefix = strs[0]
for s in strs[1:]:

7/9
while not [Link](prefix):
prefix = prefix[:-1]
return prefix

Time: O(n * m) | Space: O(1).

9. Find All Substrings


python

def all_substrings(s):
return [s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)]

Time: O(n²) | Space: O(n²).

10. String Compression (Run Length Encoding)


python

def compress(s):
res = ""
count = 1
for i in range(1, len(s)+1):
if i < len(s) and s[i] == s[i-1]:
count += 1
else:
res += s[i-1] + str(count)
count = 1
return res

Time: O(n) | Space: O(n).

11. Longest Palindromic Substring (Expand Around


Center)

8/9
python

def longest_palindrome(s):
res = ""
for i in range(len(s)):
for a, b in [(i, i), (i, i+1)]:
while a >= 0 and b < len(s) and s[a] == s[b]:
if (b-a+1) > len(res):
res = s[a:b+1]
a -= 1; b += 1
return res

Time: O(n²) | Space: O(1).

12. Check Pangram


python

def is_pangram(s):
return set('abcdefghijklmnopqrstuvwxyz') <= set([Link]())

Time: O(n) | Space: O(1).

If you want, I can now make you a “One-Page DSA String Quick Sheet” with all
patterns, tricky variations, and best approaches so you can revise all string
problems in 5 minutes before your interview.

Do you want me to prepare that PDF for you?

Hey! Looks like you sent just a dot — anything specific you want me to help with?
More string DSA questions? Or maybe array ones? Or something else for your data
engineering interview?

9/9

Common questions

Powered by AI

A string is identified as a palindrome if it reads the same backward as forward. This can be checked by comparing the string to its reverse using slicing (s[::-1]), resulting in a time complexity of O(n) and space complexity of O(n) when not done in-place since creating the reversed string requires extra space. Alternatively, comparing the string directly character by character from both ends to the middle allows O(n) time complexity and O(1) space complexity .

The first non-repeating character in a string can be identified by leveraging a frequency count of each character using a dictionary or a Counter from the collections module in Python. After populating the frequency data structure, a subsequent linear scan of the string can identify the first character with a frequency of one. This approach has a time complexity of O(n), where the cost of building the frequency map and the subsequent scan are both O(n), and space complexity of O(n) to store character counts .

To check if two strings are rotations of each other, concatenate the first string with itself and verify if the second string is a substring of this concatenated result. This method utilizes O(n) time complexity because checking if one string is a substring of another takes linear time in the combined length, and O(n) space is used to accommodate the concatenated string .

Kadane’s Algorithm is used to find the maximum sum of a contiguous subarray in an array of integers. It operates by iterating through the array, maintaining a current subarray sum, and updating the maximum sum found so far. Specifically, for each element at index i, the algorithm considers whether to add the element to the current subarray sum or start a new subarray starting at i, thus achieving O(n) time complexity and O(1) space complexity. This approach efficiently handles negative sums by resetting when a larger new subarray sum is detected .

Rotating an array by k positions involves rearranging the elements such that the elements shift to the right by k positions. This can be achieved by slicing: arr[-k:] + arr[:-k], which has time complexity O(n) and space complexity O(n). An in-place solution can reverse the whole array, reverse the first k elements, and finally reverse the rest, achieving O(1) space complexity while maintaining O(n) time complexity .

The longest common prefix of multiple strings can be determined using a vertical scanning approach, in which the prefix is iteratively constructed by comparing characters at each position across all strings. Starting with the first string as a reference, the algorithm checks each character position against others until a mismatch is found, thus building the prefix. This algorithm has a time complexity of O(n * m), where n is the minimum string length and m is the number of strings, since each character is checked once .

To find the second largest element in an array, a common approach is to remove duplicates, sort the array, and select the second last element, resulting in O(n log n) time complexity. This can be optimized to O(n) by traversing the array twice: first to find the largest element and second to find the largest element less than the maximum. This eliminates the need for sorting and uses only a constant amount of extra space .

In a sorted array, duplicates can be removed by traversing the array once and keeping a pointer for the position of the last unique element, achieving both O(n) time complexity and O(1) space complexity. For an unsorted array, duplicates can be removed by using a set to store seen elements, which requires O(n) time and O(n) space due to the necessity of using additional data structures to check for uniqueness throughout the traversal .

Reversing an array can be efficiently implemented in Python using slicing with the syntax arr[::-1]. This approach creates a reversed copy of the array, achieving a time complexity of O(n) and a space complexity of O(n). However, if the task is to reverse the array in-place using swapping, the space complexity reduces to O(1).

The intersection of two arrays can be computed using set operations in Python. By converting both arrays to sets, their intersection can be found using the '&' operator, resulting in a time complexity of O(n + m) and a space complexity of O(min(n, m)), where n and m are the lengths of the two arrays .

You might also like