? Step 1 - Python Programming & Scripting
? Step 1 - Python Programming & Scripting
Ans. Inner join will have more number of rows compared to outer join.
Inner join returns only the matching rows between two tables
Outer join returns all rows from one table and matching rows from the other table
Example: If Table A has 10 rows and Table B has 8 rows, inner join will have maximum 8 rows
while outer join can have maximum 10 rows
📌 Question: Which join operation will result in the largest number of rows?
✅ Correct Answer:
A CROSS JOIN (also called Cartesian Join) will result in the largest number of rows because it combines
every row of one table with every row of the other table.
LEFT/RIGHT OUTER JOIN → returns all rows from one table plus matching rows from the other.
CROSS JOIN → returns the maximum rows because it doesn’t require matching conditions.
👉 So the largest number of rows comes from CROSS JOIN, not INNER JOIN or OUTER JOIN.
Do you want me to reframe your example with all join types (inner, left, right, full, cross) so it’s crystal
clear?
Q. What is the difference between a product life cycle and a software life cycle?
Ans. Product life cycle refers to stages a product goes through from introduction to withdrawal,
while software life cycle refers to stages a software goes through from development to
retirement.
Product life cycle includes introduction, growth, maturity, and decline stages.
Software life cycle includes planning, development, testing, deployment, and maintenance
stages.
Product life cycle focuses on physical products, while software life cycle focuses on software
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/122
development.
Product life cycle involves marketing, sales, and customer feedback, while software life cycle
involves coding, testing, and user feedback.
Your answer is mostly correct 👍, but it can be made sharper and more structured. Here’s a refined
version:
📌 Question: What is the difference between a product life cycle and a software life
cycle?
✅ Correct Answer:
1. Definition:
Product Life Cycle (PLC): Refers to the stages a product (physical or software) goes through in
the market, from introduction to withdrawal.
Software Development Life Cycle (SDLC): Refers to the process of planning, creating, testing,
deploying, and maintaining software.
2. Stages:
3. Focus:
PLC: Focuses on market and business aspects (sales, demand, competition, customer
adoption).
SDLC: Focuses on technical aspects (coding, testing, maintenance, bug fixing, version
upgrades).
4. Involves:
👉 In short:
Product Life Cycle = market journey of a product.
Would you like me to also create a side-by-side comparison table (PLC vs SDLC) so it’s super easy to
remember for exams/interviews?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/122
on Monday i have a technical interview and i have told them about my resume and they told me
they ask me programming question and coding programs so what i should do dsa or python
and sql or both
Got it👍 thanks for sharing — since your technical interview is on Monday, here’s the smart way to
prepare in limited time:
🎯 What to Focus On
1. DSA (Data Structures & Algorithms)
Almost every technical interview checks your problem-solving skills.
Focus on arrays, strings, hashing, recursion, sorting, searching, linked list, stack, queue,
trees, and basic dynamic programming.
2. Python
Since you know Python, be ready to code solutions in Python.
Review syntax, list/dict operations, loops, functions, OOP basics, and exception handling.
3. SQL
Many companies ask SQL queries along with coding.
Revise SELECT, WHERE, GROUP BY, HAVING, ORDER BY, JOINS, subqueries, aggregate
functions.
Evening → Mock coding practice (pick 3–4 problems and solve them with timer).
Monday (Before Interview):
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/122
Revise concepts, not new topics.
👉 So the answer: Do both DSA + Python + SQL (all three, but focus more on DSA + Python coding, and
revise SQL).
Do you want me to quickly make you a list of 15 must-do coding questions (mix of DSA + SQL) that are
most likely to come up in interviews?
company name is xalt analytics so can you prepare me for that interview
Great question — yes, I can help you prepare specifically for Xalt Analytics. From what I found, here’s
what you should focus on plus mock questions & a plan to boost your chances.
They are in data analytics, AI/ML, text & image analytics, unstructured data, dashboards, LLM
& NLP. Xalt Analytics+2
They do big data, unstructured & structured data processing, dashboarding, model creation.
Xalt Analytics+2
They are relatively small to medium size, so your role might require you to wear multiple hats
(coding + data + maybe some infrastructure) TechBehemoths+1
On interview experiences, they do “aptitude + coding + elimination rounds” for some candidates.
Glassdoor
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/122
Topic Why it’s important for Xalt What subtopics to focus on
Coding / DSA
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/122
9. Join & aggregation
Given two tables (Orders, Customers), find customers who placed more than 5 orders.
10. Running total / window function
“Show cumulative sum of sales over time per region.”
ML / Data / Case
Morning Solve 2 DSA problems (medium) Warm-up: solve 1 easy coding problem
Late
Do 2 SQL queries / window function practice Review SQL & mental formulas
Morning
Learn or review an ML/NLP concept (e.g. TF-IDF or Review projects, problems you’ve solved
Afternoon
embeddings) before
Mock interview: pick one coding + one case (data Go through notes, relax, don’t learn brand
Evening
pipeline / text) new topics
Also:
Practice explaining your past projects clearly (problem, approach, challenges, results).
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/122
If stuck, tell them what you're thinking; sometimes partial solutions or extensions are fine.
In data questions, talk about edge cases (NULLs, duplicates, empty sets).
For ML / pipeline / scenario questions, structure your answer: problem → approach → trade-offs →
evaluation.
Be honest if you don’t know something; show you can reason or propose what you would do.
If you like, I can simulate a mock interview session with 5 questions (coding + SQL + ML) right now.
Want me to start that with you?
no lets start studying all topic line by line that you mentioned
Perfect 💯 That’s the best approach! We’ll go line by line, topic by topic, and I’ll explain + give you short
examples/exercises so you understand and retain them before Monday.
Here’s the roadmap we’ll follow (based on the topics I listed for Xalt Analytics):
📚 Study Roadmap
1. Python programming & scripting (core syntax, lists/dicts, OOP basics, Pandas/Numpy overview)
2. Data Structures & Algorithms (DSA) (arrays, strings, recursion, sorting, trees, heaps, DP basics)
3. SQL & Data querying (joins, GROUP BY, HAVING, window functions, interview-style queries)
6. NLP / Text Analytics Basics (tokenization, TF-IDF, embeddings, sentiment analysis, transformers
overview)
7. Project & Case Study Prep (your resume projects + scenario-based Qs)
yes
Got it👍 we’ll start with Python → then DSA → then SQL → then Stats → then ML → then NLP →
then Projects.
I’ll keep it short, structured, with examples + mini exercises so you don’t just read but also practice.
python
nums = [1, 2, 3]
nums.append(4) # [1, 2, 3, 4]
nums.remove(2) # [1, 3, 4]
2. Control Structures
if-else, for loop, while loop, break/continue
Example:
python
for i in range(5):
if i == 3:
continue
print(i)
3. Functions
default args, return values, lambda
Example:
python
def greet(name="Guest"):
return f"Hello {name}"
4. OOP Basics
classes, objects, inheritance
Example:
python
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Bark")
Dog().sound() # Bark
5. Exception Handling
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/122
python
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Done")
python
import pandas as pd
4. Use Pandas to read a CSV file and print only the first 5 rows (.head()).
👉 Now, do you want me to explain these mini exercises with solutions immediately, or should I first
give you practice questions, let you attempt, then I provide solutions?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/122
5. File Handling
🔹 1. Python Basics
Variables & Data Types
python
x = 10 # int
x = "Hello" # str
Built-in types: int, float, str, bool, None, list, tuple, set, dict
Operators
Arithmetic: + - * / // % **
👉 Example:
python
a, b = 10, 20
print(a + b) # 30
print(a // 3) # 3
print(a ** 2) # 100
print("n" in "Nishit") # True
🔹 2. Collections
List
python
nums = [5, 2, 8]
nums.append(10) # [5, 2, 8, 10]
nums.sort() # [2, 5, 8, 10]
Tuple
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/122
Ordered, immutable
python
t = (1, 2, 3)
print(t[1]) # 2
Set
python
s = {1, 2, 2, 3}
print(s) # {1, 2, 3}
Dictionary
python
🔹 3. Functions
Normal Function
python
python
def greet(name="Guest"):
print(f"Hello {name}")
greet("Nishit")
greet() # Hello Guest
Lambda (anonymous)
python
square = lambda x: x * x
print(square(5)) # 25
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/122
Map, Filter, Reduce
python
nums = [1, 2, 3, 4]
print(list(map(lambda x: x*x, nums))) # [1, 4, 9, 16]
print(list(filter(lambda x: x%2==0, nums))) # [2, 4]
from functools import reduce
print(reduce(lambda a,b: a+b, nums)) # 10
🔹 4. OOP in Python
Class & Object
python
class Car:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
def show(self):
print(f"{self.brand} runs at {self.speed} km/h")
c1 = Car("Tesla", 200)
c1.show()
Inheritance
python
class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Bark")
Dog().sound()
Encapsulation
Polymorphism
🔹 5. Exception Handling
python
try:
x = 10 / 0
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/122
except ZeroDivisionError as e:
print("Error:", e)
finally:
print("Always runs")
🔹 6. File Handling
python
🔹 7. Libraries (Basics)
NumPy
python
import numpy as np
arr = np.array([1,2,3])
print(arr.mean())
Pandas
python
import pandas as pd
data = {"Name": ["A", "B"], "Marks": [85, 90]}
df = pd.DataFrame(data)
print(df.head())
Absolutely! Let’s go deep into each Python topic, with examples, edge cases, best practices, and tips
for interviews. I’ll break it down topic by topic so you really understand, not just memorize.
python
x = 10 # int
x = "Hello" # str (reassigned)
python
a = [1, 2, 3]
b = a # both refer to same list (mutable)
b.append(4)
print(a) # [1, 2, 3, 4] → careful with references!
Operators
Arithmetic: + - * / // % **
// → floor division, rounds down
% → modulus
** → exponentiation
Comparison: ==, !=, <, >, <=, >=
python
x = [1, 2]
y = [1, 2]
print(x == y) # True → values same
print(x is y) # False → different objects
Control Structures
if-elif-else
Interview tip: Python allows for-else and while-else, which often confuses beginners.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/122
python
for i in range(3):
print(i)
else:
print("Loop completed") # runs only if loop NOT broken
Common methods:
python
lst = [5, 3, 8]
lst.append(10)
lst.insert(1, 7)
lst.remove(3)
lst.pop() # removes last
lst.sort() # in-place sort
lst.reverse()
lst.copy() # shallow copy
Slicing
python
lst = [0,1,2,3,4,5]
print(lst[1:4]) # [1,2,3]
print(lst[::-1]) # reverse
Tuple
Immutable, ordered
python
Set
python
a = {1,2,3}
b = {2,3,4}
print(a | b) # union {1,2,3,4}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/122
print(a & b) # intersection {2,3}
print(a - b) # difference {1}
Dictionary
python
d = {"name":"Nishit", "age":22}
d.keys()
d.values()
d.items()
d.get("name") # safer than d["name"]
d.pop("age")
python
python
Default Arguments
python
def greet(name="Guest"):
print(f"Hello {name}")
greet()
greet("Nishit")
Keyword Arguments
python
Variable Arguments
python
Lambda Functions
python
python
nums = [1,2,3,4]
print(list(map(lambda x: x*x, nums))) # [1,4,9,16]
print(list(filter(lambda x: x%2==0, nums))) # [2,4]
from functools import reduce
print(reduce(lambda a,b: a+b, nums)) # 10
Interview tip: These are commonly asked in coding rounds for list/array manipulation.
python
class Employee:
company = "Xalt" # class attribute
def __init__(self, name, salary):
self.name = name # instance attribute
self.salary = salary
def show(self):
print(self.name, self.salary)
Inheritance
python
class Manager(Employee):
def bonus(self):
print(self.salary * 0.1)
Encapsulation
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/122
Use _protected (convention) or __private (name mangling) to restrict access
python
class Test:
def __init__(self):
self.__secret = 42
def reveal(self):
return self.__secret
Polymorphism
python
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
for animal in [Dog(), Cat()]:
animal.sound() # Bark, Meow
python
try:
a = int("abc")
except ValueError:
print("Value error")
except Exception as e:
print("Other error", e)
finally:
print("Done")
python
def check_age(age):
if age < 18:
raise ValueError("Too young")
check_age(15) # ValueError
# Writing
with open("file.txt", "w") as f:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/122
f.write("Hello World\n")
f.write("Second line")
# Reading
with open("file.txt", "r") as f:
print(f.read())
python
import numpy as np
arr = np.array([1,2,3])
print(arr + 2) # [3,4,5]
Avoid using for loops with NumPy; use vectorized operations for speed.
Pandas
python
import pandas as pd
data = {"Name":["A","B"], "Marks":[85,90]}
df = pd.DataFrame(data)
print(df.head()) # first 5 rows
print(df.describe()) # summary stats
print(df['Marks'].mean())
✅ This is Python deep dive. If you understand all of this well, you’ll be ready for coding questions,
data manipulation, and even some ML pipelines.
Next step: I suggest we start solving Python practice problems (arrays, strings, dicts, OOP, lambda,
Pandas) so your foundation becomes rock solid.
Do you want me to start with 10 Python coding problems for practice now?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/122
Interview tip: Understand difference between modes: r, w, a, r+, w+, a+
Encapsulation
Variable Arguments
this are the topics i don't understand well so explain me each topic in deep and easylt]y i can
understand
Perfect! Let’s break down each of these topics carefully so you not only understand them but also
remember them for interviews. I’ll use simple examples, edge cases, and “why it matters” notes.
a append Open for writing at the end of file. Creates if not exists.
r+ read/write Open for reading & writing. File must exist.
w+ write/read Open for writing & reading. Creates if not exists. Overwrites existing file.
Examples:
python
# r mode
with open("data.txt", "r") as f:
print(f.read()) # reads all content
# w mode
with open("data.txt", "w") as f:
f.write("Hello World") # overwrites existing content
# a mode
with open("data.txt", "a") as f:
f.write("\nNew Line") # adds at the end
# r+ mode
with open("data.txt", "r+") as f:
content = f.read()
f.write("\nAdded Text") # can read & write
# w+ mode
with open("data.txt", "w+") as f:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/122
f.write("Overwrite")
f.seek(0)
print(f.read()) # read new content
# a+ mode
with open("data.txt", "a+") as f:
f.write("\nAppend")
f.seek(0)
print(f.read()) # read entire content
Interview Tip:
Example:
python
class Employee:
def __init__(self, name, salary):
self._name = name # protected
self.__salary = salary # private
e = Employee("Nishit", 50000)
print(e._name) # works, but convention says "don’t use"
# print(e.__salary) # ERROR: private attribute
print(e._Employee__salary) # works via name mangling
Interview Tip:
*args
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/122
python
def add_numbers(*args):
total = 0
for num in args:
total += num
return total
print(add_numbers(1,2,3)) # 6
print(add_numbers(4,5)) # 9
**kwargs
python
def student_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
python
Interview Tip:
python
Examples:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/122
python
# Squares of numbers
squares = {x: x*x for x in range(5)}
print(squares) # {0:0, 1:1, 2:4, 3:9, 4:16}
Interview Tip:
Dict comprehension {key: value for ...} for concise dictionary creation
I can also make a visual diagram + small exercises for all 4 topics so you can practice and remember
easily — it will make them stick for interviews.
Do you want me to do that next?
Next step: I suggest we start solving Python practice problems (arrays, strings, dicts, OOP,
lambda, Pandas) so your foundation becomes rock solid.
lets do that
Awesome 🚀That’s exactly the right move — let’s move from theory → practice problems so you’re
interview-ready.
We’ll cover arrays, strings, dicts, OOP, lambda, Pandas step by step with increasing difficulty.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/122
python
def reverse_array(arr):
return arr[::-1]
print(reverse_array([1,2,3,4,5])) # [5,4,3,2,1]
python
def find_min_max(arr):
return min(arr), max(arr)
print(find_min_max([4,7,1,9,3])) # (1, 9)
python
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam")) # True
print(is_palindrome("nishit")) # False
python
def char_frequency(s):
freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1
return freq
print(char_frequency("banana"))
# {'b':1, 'a':3, 'n':2}
python
def remove_duplicates(arr):
return list(set(arr))
print(remove_duplicates([1,2,2,3,4,4,5])) # [1,2,3,4,5]
python
python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
return f"{self.brand} {self.model}"
🔹 Step 4: Pandas
Q9. Create a DataFrame and perform basic operations
python
import pandas as pd
data = {
"Name": ["A", "B", "C"],
"Age": [25, 30, 22],
"Score": [85, 90, 78]
}
df = pd.DataFrame(data)
✅ These cover the most asked Python interview problems in your range (arrays, strings, dicts, OOP,
lambda, Pandas).
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/122
👉 My suggestion: Let’s solve 10 problems per topic daily → in 3 days you’ll be interview-ready.
Do you want me to now give you a set of 10 array + string practice problems to solve (I’ll guide with
hints, you code)?
ok
Input: "programming"
Output: {'r': 2, 'g': 2, 'm': 2}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/122
Q6. Move all zeros to the end of array
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Input: "swiss"
Output: "w"
Input: ["flower","flow","flight"]
Output: "fl"
def reverse_string(s):
rev = []
s = s.split()
for word in s[::-1]:
rev.append(word[::-1])
return' '.join(rev)
Nice try 👍 but your code is slightly off because of two issues:
1. Indentation of return → It’s inside the loop, so it returns after the first iteration only.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/122
2. Logic → You’re reversing each word too, but the problem was only to reverse the word order (not
letters inside).
✅ Correct version:
python
def reverse_string(s):
words = s.split() # ['I', 'love', 'Python']
rev = words[::-1] # ['Python', 'love', 'I']
return ' '.join(rev) # "Python love I"
Output:
css
Python love I
👉 If you also wanted to reverse letters in each word (like "I evol nohtyP"), then your logic with
word[::-1] would be correct — just fix the return indentation:
python
def reverse_string(s):
rev = []
for word in s.split()[::-1]:
rev.append(word[::-1]) # reverse each word
return ' '.join(rev)
Output:
css
nohtyP evol I
❓ Do you want me to give you the step-by-step solutions for all 10 problems we listed, or should we
go one by one (you try → I correct → move to next)?
def sort_array(arr):
arr.sort()
arr.pop()
return arr[-1]
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/122
Good attempt 🙌 but let’s carefully check what your code is doing:
Your Code Flow
python
👉 This works and returns 45, but there are two issues in an interview context:
def second_largest(arr):
unique_arr = list(set(arr)) # remove duplicates
unique_arr.sort() # sort
return unique_arr[-2] # second last
def second_largest(arr):
first = second = float('-inf')
for num in arr:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
return second
⚡ This runs in O(n) (faster than sorting, which is O(n log n)).
👉 Do you want me to explain the efficient O(n) logic in detail (step by step how it tracks first and
second largest), or should we move to Q3 (check anagrams)?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/122
def sort_array(arr):
arr.sort()
return arr[-2]
Yes 👌 this version is shorter and correct for the case without duplicates.
Let’s test it:
python
def sort_array(arr):
arr.sort()
return arr[-2]
Steps:
python
def sort_array(arr):
arr = list(set(arr)) # remove duplicates
arr.sort()
return arr[-2]
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/122
def anagram(s1, s2):
s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
return sorted(s1) == sorted(s2)
Perfect! 🎯
Your solution is clean, correct, and interview-friendly. Let’s break it down so you remember it for
Monday:
✅ Your Code
python
🔎 Why it works
1. replace(" ", "") → removes spaces so "listen " = "listen".
2. .lower() → makes it case-insensitive ("Listen" == "silent").
3. sorted(s1) → converts string into a sorted list of characters.
"listen" → ['e', 'i', 'l', 'n', 's', 't']
→ ['e', 'i', 'l', 'n', 's', 't']
✅
"silent"
Equal → so strings are anagrams.
⚠️ Interview Tip
Sorting is O(n log n).
If they ask for a faster O(n) approach, use a dictionary (frequency count).
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/122
👉 Do you want to try Q4 (Find duplicate characters in a string) yourself first, or should I walk you
through the solution?
def duplicate_characters(s):
seen = set()
duplicate_characters = set()
for char in s:
if char in seen:
duplicate_characters.add(char)
else:
seen.add(char)
return list(duplicate_characters)
print(duplicate_characters("programming"))
Nice attempt 💯but your function is returning too early because of the return being inside the for loop.
That means it exits after checking only the first character.
❌ Your version
python
def duplicate_characters(s):
seen = set()
duplicate_characters = set()
for char in s:
if char in seen:
duplicate_characters.add(char)
else:
seen.add(char)
return list(duplicate_characters) # 🚨 Problem: return inside loop
✅ Fixed version
python
def duplicate_characters(s):
seen = set()
duplicates = set()
for char in s:
if char in seen:
duplicates.add(char)
else:
seen.add(char)
return list(duplicates)
print(duplicate_characters("programming"))
Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/122
css
def duplicate_characters(s):
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
return {char: count for char, count in freq.items() if count > 1}
print(duplicate_characters("programming"))
Output:
arduino
👉 Do you want me to now guide you on Q5 (Find missing number in an array 1 to N)?
Of course 👍 let’s carefully break down the duplicate character code step by step so it’s crystal clear.
✅ Version 1: Return just the duplicates (as a list)
python
def duplicate_characters(s):
seen = set()
duplicates = set()
for char in s:
if char in seen: # If we already saw the character before
duplicates.add(char) # It's a duplicate → add it to duplicates
else:
seen.add(char) # First time seeing this char → add to seen
return list(duplicates) # Finally return all duplicates
def duplicate_characters(s):
freq = {} # dictionary to count occurrences
for char in s:
freq[char] = freq.get(char, 0) + 1 # increase count for each char
return {char: count for char, count in freq.items() if count > 1}
How it works:
Example: "programming"
⚡ So the first version tells you “which letters are duplicates”, while the second version tells you “which
letters are duplicates AND how many times they appear”.
👉 Do you want to practice Q5 (Find missing number in an array 1..N) next, or should I give you a few
more string-related problems first so you feel 100% comfortable?
def missing_numbers(n,arr):
expected_sum = (n*(n+1))//2
actual_sum = sum(arr)
return expected_sum - actual_sum
n=5
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 34/122
arr = [1,2,3,5]
print(missing_numbers(n, arr))
✅ Your Code
python
n = 5
arr = [1,2,3,5]
print(missing_numbers(n, arr))
🔎 How it works
Formula for sum of first n natural numbers = n*(n+1)//2
For n=5 → 5*6//2 = 15
sum(arr) = 1+2+3+5 = 11
Missing number = 15 - 11 = 4 ✅
⚠️ Things to Note (Interview Tips)
1. This method works only if exactly ONE number is missing.
If multiple numbers are missing, this won’t work.
Eg: [1,3,5] → Expected sum=15, actual=9, difference=6 → but missing {2,4} not 6.
2. For multiple missing numbers, you’d need a different approach (like using sets).
👉 Do you want me to now guide you through Q6 (Move all zeros to the end of array), or should we
first explore a harder version of missing numbers (like handling unsorted arrays with multiple missing
values)?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 35/122
def move_zeros(arr):
arr = [x for x in arr if x!=0]
arr += [0]*(len(arr) - len(arr))
return arr
print(move_zeros([0,1,0,3,12]))
Ah, I see what you’re trying to do 😅— the idea is correct (filter out zeros and append them at the end),
but there’s a small bug in your code:
❌ Your Code
python
✅ Correct Version
python
def move_zeros(arr):
n = len(arr)
arr = [x for x in arr if x != 0] # remove zeros
arr += [0]*(n - len(arr)) # append zeros at the end
return arr
Output:
csharp
[1, 3, 12, 0, 0]
def move_zeros(arr):
last_non_zero = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[i], arr[last_non_zero] = arr[last_non_zero], arr[i]
last_non_zero += 1
return arr
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 36/122
print(move_zeros([0,1,0,3,12])) # [1, 3, 12, 0, 0]
💡 Interview Tip:
Be ready to explain both methods: list comprehension (easy) and in-place (optimized).
Often asked in array manipulation / two-pointer questions.
Do you want to try Q7 (Check if string has all unique characters) next?
def unique_characters(s):
s = s.lower()
a = list(s)
b = list(set(a))
return a == b
print(unique_characters("Hello World"))
def unique_characters(s):
s = s.replace(" ", "").lower() # remove spaces, lowercase
seen = set()
for char in s:
if char in seen:
return False # duplicate found
seen.add(char)
return True # no duplicates
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 37/122
print(unique_characters("abcdef")) # True
print(unique_characters("hello")) # False
print(unique_characters("Hello World")) # False
🔎 How it works
1. replace(" ", "") → remove spaces
2. lower() → make case-insensitive
3. Loop through each char:
If already in seen → not unique → return False
Else, add to seen
4. If loop completes → all characters are unique → return True
💡 Interview Tip:
Using a set is O(1) for lookup → total time = O(n)
Don’t use list(set(...)) == list(...) → wrong for order and duplicates
def non_repeating_characters(s):
s.lower()
s = s.replace(" ", "")
seen = set()
for char in s:
if char in seen:
seen.add(char)
return seen[1]
seen.remove(seen[0])
return None
print(non_repeating_characters("Hello World"))
Ah, I see what you’re trying to do 😅 — your code has a few conceptual issues:
❌ Problems in your code
1. s.lower() → doesn’t change s because strings are immutable. You need s = s.lower().
2. You’re trying to do seen[0] or seen[1] on a set, but sets are unordered → you cannot index them.
3. Logic for detecting non-repeating characters is incorrect: you’re removing/adding from the set
incorrectly.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 38/122
✅ Correct Approach
We need to find the first character that occurs exactly once.
python
def non_repeating_character(s):
s = s.lower().replace(" ", "") # lowercase & remove spaces
freq = {} # dictionary to count frequency
print(non_repeating_character("Hello World")) # h
🔎 How it works
1. Count frequency of each character using a dictionary (O(n)).
2. Loop through string again and return the first char with count 1.
k=3
print(rot_array([1,2,3,4,5,6,7], k+1))
Ah, I see what you’re trying 😎, but let’s carefully check the logic and output.
❌ Issues in your code
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 39/122
python
You wrote k+1 → that will rotate 4 steps instead of 3 (might be a mistake).
python
arr = [1,2,3,4,5,6,7]
k = 3
print(rotate_array(arr, k)) # [5,6,7,1,2,3,4]
🔎 How it works
1. arr[-k:] → last k elements → [5,6,7]
2. arr[:-k] → remaining elements → [1,2,3,4]
3. Combine → [5,6,7,1,2,3,4] ✅
4. k = k % n → ensures it works even if k > len(arr)
python
💡 Interview Tip:
Always clarify left or right rotation.
Use k % n to handle large rotations.
Do you want to now solve Q10 (Longest common prefix among strings)?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 40/122
def longest_common_prefix(strs):
if not strs:
return ""
prefix = strs[0]
for s in strs[1:]:
while s.startswith(prefix) == False:
prefix = prefix[:-1]
if not prefix:
return ""
return prefix
Perfect! 🎯 Your solution for Longest Common Prefix is correct and very interview-friendly.
Let’s break it down carefully so you fully understand it:
✅ Your Code
python
def longest_common_prefix(strs):
if not strs: # Edge case: empty list
return ""
prefix = strs[0] # Start with the first string as prefix
for s in strs[1:]: # Compare with the rest of the strings
while not s.startswith(prefix): # While current string doesn't start with prefix
prefix = prefix[:-1] # Remove last character from prefix
if not prefix:
return "" # No common prefix
return prefix
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 41/122
✅ Interview Tips
Time complexity: O(S) where S is the sum of all characters in all strings.
Handles edge cases:
ok
Perfect! 🚀 Let’s move to Dictionaries & Lambda in Python — these are super important for interviews.
We’ll do 5–6 practice problems, step by step, with explanations.
python
arr = [1,2,2,3,3,3,4]
# Using dictionary
freq = {}
for x in arr:
freq[x] = freq.get(x,0) + 1
# Using Counter
from collections import Counter
print(Counter(arr)) # Counter({3:3, 2:2, 1:1, 4:1})
python
# Sorted by values
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 42/122
sorted_d = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted_d) # {'b':1, 'c':2, 'a':3}
python
d1 = {'a':1, 'b':2}
d2 = {'b':3, 'c':4}
# Older way
merged = {**d1, **d2}
print(merged) # {'a':1, 'b':3, 'c':4}
python
max_val = max(d.values())
keys = [k for k,v in d.items() if v==max_val]
print(keys) # ['b', 'c']
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 43/122
python
💡 Interview Tip:
Always know dict methods: .items(), .keys(), .values(), .get(), .update().
Lambda + dict → very common in coding rounds.
If you want, we can now move to OOP practice problems (classes, inheritance, encapsulation), which
are very important for your interview at Xalt Analytics.
ok
Problem: Create a Car class with attributes brand and model. Add a method display() to show the car’s
info.
python
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def display(self):
return f"{self.brand} {self.model}"
# Create object
c = Car("Tesla", "Model S")
print(c.display()) # Tesla Model S
Q2. Encapsulation
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 44/122
Problem: Make salary private and provide a method to access it.
python
class Employee:
def __init__(self, name, salary):
self.name = name
self.__salary = salary # private variable
def get_salary(self):
return self.__salary
e = Employee("Nishit", 50000)
print(e.get_salary()) # 50000
Q3. Inheritance
python
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, I am {self.name}"
class Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
def student_info(self):
return f"{self.name} is in grade {self.grade}"
s = Student("Nishit", "A")
print(s.greet()) # Hello, I am Nishit
print(s.student_info()) # Nishit is in grade A
python
class MathOperations:
@staticmethod
def add(a, b):
return a + b
@classmethod
def multiply(cls, a, b):
return a * b
print(MathOperations.add(2,3)) # 5
print(MathOperations.multiply(2,3)) # 6
python
class Calculator:
def add(self, *args):
return sum(args)
calc = Calculator()
print(calc.add(1,2,3)) # 6
print(calc.add(4,5)) # 9
If you want, we can now do a batch of 5–6 Python OOP coding problems that are very commonly
asked in interviews.
Do you want me to do that next?
ok
Perfect! 🚀
Let’s do 5–6 Python OOP coding problems step by step, with explanations. These are
commonly asked in interviews, especially for your profile at Xalt Analytics.
python
class BankAccount:
def __init__(self, owner, balance=0):
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 46/122
self.owner = owner
self.balance = balance
def display_balance(self):
return f"{self.owner}'s balance: {self.balance}"
# Test
acc = BankAccount("Nishit", 1000)
print(acc.deposit(500)) # Deposited 500. New balance: 1500
print(acc.withdraw(200)) # Withdrew 200. New balance: 1300
print(acc.display_balance()) # Nishit's balance: 1300
python
class Employee:
def __init__(self, name, salary):
self._name = name # protected
self.__salary = salary # private
def get_salary(self):
return self.__salary
e = Employee("Nishit", 50000)
print(e._name) # Nishit (accessible, but protected)
print(e.get_salary()) # 50000
e.set_salary(60000)
print(e.get_salary()) # 60000
python
class Vehicle:
def fuel_type(self):
return "Generic fuel"
class Car(Vehicle):
def fuel_type(self):
return "Petrol"
v = Vehicle()
c = Car()
print(v.fuel_type()) # Generic fuel
print(c.fuel_type()) # Petrol
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 47/122
Child class overrides parent method → polymorphism
python
class Circle:
pi = 3.14
def area(self):
return Circle.pi * self.radius**2
@classmethod
def change_pi(cls, new_pi):
cls.pi = new_pi
@staticmethod
def greet():
return "Welcome to Circle class!"
c = Circle(5)
print(c.area()) # 78.5
Circle.change_pi(3)
print(c.area()) # 75
print(Circle.greet()) # Welcome to Circle class!
python
class Calculator:
def add(self, *args):
return sum(args)
calc = Calculator()
print(calc.add(1,2,3,4)) # 10
print(calc.multiply(a=2, b=3, c=4)) # 24
💡 Interview Tip:
They may give small real-world scenarios like:
“Create Library class with Books”
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 48/122
“Create Student class with grades and average calculation”
Be ready to use OOP + methods + variable arguments + encapsulation.
If you want, we can next do Python Pandas practice problems, which are also very important for Xalt
Analytics interviews.
Do you want to continue with Pandas?
ok
Perfect! 🚀Let’s move to Python Pandas practice problems, step by step. These are very important
for analytics/data-focused interviews like Xalt Analytics.
We’ll cover 5–6 key problems with explanations.
python
import pandas as pd
data = {
'Name': ['Nishit', 'Palak', 'Rohan'],
'Age': [21, 22, 20],
'Department': ['IT', 'HR', 'Finance']
}
df = pd.DataFrame(data)
print(df)
Output:
markdown
python
print(df['Name'])
Output:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 49/122
pgsql
0 Nishit
1 Palak
2 Rohan
Name: Name, dtype: object
python
Output:
markdown
python
Output:
markdown
python
Output:
markdown
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 50/122
1 Palak 22 HR 60000 66000.0
2 Rohan 20 Finance 55000 60500.0
python
Output:
yaml
Department
Finance 55000.0
HR 60000.0
IT 50000.0
Name: Salary, dtype: float64
We have now covered arrays, strings, dictionaries, lambda, OOP, and pandas in depth. 🔥
If you want, we can do a mini mock coding interview, where I’ll give you problems one by one, and
you try to solve them like in a real interview.
ok
Perfect! 🎯 Let’s do a mock coding interview session. I’ll give you one problem at a time, you try to
solve it, then I’ll review and explain.
We’ll simulate a real technical interview, covering arrays, strings, dicts, OOP, and pandas.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 51/122
Question:
Given an array of integers, return a new array such that each element at index i is the product of all the
numbers in the original array except the one at i.
Example:
makefile
Input: [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Try writing the code in Python. Once you do, share it here and I’ll review it.
no clue\
No worries! 😎 Let’s solve it step by step. This is a classic “product of array except self” problem.
Problem Recap
Input: [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Constraint: No division.
python
So:
output[0] = 2*3*4 = 24
output[1] = 1*3*4 = 12
etc.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 52/122
python
def product_except_self(arr):
n = len(arr)
output = [1]*n
# Prefix products
prefix = 1
for i in range(n):
output[i] = prefix
prefix *= arr[i]
# Suffix products
suffix = 1
for i in range(n-1, -1, -1):
output[i] *= suffix
suffix *= arr[i]
return output
# Test
print(product_except_self([1, 2, 3, 4])) # [24, 12, 8, 6]
🔎 How it works
Prefix loop:
Start prefix = 1
i=0: output[0] = 1 → prefix = 1*1 = 1
i=1: output[1] = 1 → prefix = 1*2 = 2
i=2: output[2] = 2 → prefix = 2*3 = 6
i=3: output[3] = 6 → prefix = 6*4 = 24
Suffix loop:
Start suffix = 1
i=3: output[3] *= 1 → 6*1 = 6, suffix = 1*4 = 4
If you want, we can move to Problem 2, a string manipulation question, to continue the mock
interview.
Do you want to do that next?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 53/122
ok
Question:
Given a string, find the first non-repeating character and return its index. If it doesn’t exist, return -1.
Example:
vbnet
Input: "leetcode"
Output: 0 # 'l' is the first non-repeating character
Input: "loveleetcode"
Output: 2 # 'v' is the first non-repeating character
Try writing the Python code. Once you do, share it here and I’ll review it.
If you want, I can also solve it step by step for you. Do you want me to do that?
def non_repeating_index(s):
s = s.lower()
s = s.replace(" ", "")
seen = {}
for char in s:
seen[char] = seen.get(char, 0) + 1
for char in s:
if seen[char] == 1:
return f"{s.index(char)} # '{char}' is the first non-repeating character"
return -1
print(non_repeating_index("leetcode"))
Perfect! 🎯
Your code is almost perfect and follows the correct logic. Let’s break it down so you fully
understand it:
✅ Your Code
python
def non_repeating_index(s):
s = s.lower() # make case-insensitive
s = s.replace(" ", "") # remove spaces
seen = {}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 54/122
# Count frequency of each character
for char in s:
seen[char] = seen.get(char, 0) + 1
print(non_repeating_index("leetcode"))
Output:
sql
🔎 How it works
1. Frequency dictionary:
python
python
def non_repeating_index(s):
s = s.lower().replace(" ", "")
seen = {}
for char in s:
seen[char] = seen.get(char, 0) + 1
print(non_repeating_index("leetcode"))
💡 Interview Tip:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 55/122
Mention time complexity: O(n) → one pass to count + one pass to find index.
Space complexity: O(n) → for dictionary.
ok
Question:
python
import pandas as pd
data = {
'Name': ['Nishit', 'Palak', 'Rohan', 'Sneha', 'Amit'],
'Department': ['IT', 'HR', 'IT', 'Finance', 'HR'],
'Salary': [50000, 60000, 55000, 65000, 62000]
}
df = pd.DataFrame(data)
Tasks:
Try writing the Pandas code for this. Once you do, share it here and I’ll review it.
If you want, I can solve it step by step for you now. Do you want me to solve it?
data1 = {
'Name': ['Nishit', 'Palak', 'Rohan', 'Sneha', 'Amit'],
'Department': ['IT', 'HR', 'IT', 'Finance', 'HR'],
'Salary': [50000, 60000, 55000, 65000, 62000]
}
df = pd.DataFrame(data1)
print(df['Department'].value_counts())
grouped = df.groupby('Department')['Salary'].mean()
print(grouped)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 56/122
print(df[df['Salary'] > ])
Got it! 😅I see what you’re trying to do, but your last line is incomplete (df[df['Salary'] > ]). Let’s fix it
and solve the full problem step by step.
python
import pandas as pd
data1 = {
'Name': ['Nishit', 'Palak', 'Rohan', 'Sneha', 'Amit'],
'Department': ['IT', 'HR', 'IT', 'Finance', 'HR'],
'Salary': [50000, 60000, 55000, 65000, 62000]
}
df = pd.DataFrame(data1)
Output:
yaml
python
Output:
css
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 57/122
🔹 How it works
1. groupby('Department')['Salary'].mean() → computes average salary per department.
2. transform('max') → returns a Series of max salary aligned with original DataFrame.
3. Filter df[df['Salary'] == max_salary_per_dept] → gives top earners per department.
💡 Interview Tip:
Always clarify if they want all top earners or just one.
Use groupby + transform to avoid writing loops → efficient for large datasets.
If you want, we can now do Problem 4 – Lambda + Dict problem, which is also very common in Xalt
Analytics coding rounds.
ok
Question:
You have a dictionary of students and their scores:
python
students = {'Nishit': 85, 'Palak': 92, 'Rohan': 78, 'Sneha': 92, 'Amit': 70}
Tasks:
i think i am week in lambda i am not clearly understand the lambda and also the syntext
No worries! 😎 Let’s break lambda functions down clearly and step by step so you get it fully.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 58/122
🔹 Lambda Functions in Python
1. What is a lambda function?
python
python
add = lambda x, y: x + y
print(add(3, 5)) # 8
python
python
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9, 16]
python
nums = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # [2, 4]
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 59/122
Can sort a list of tuples or dictionary by a key.
python
python
# Max score
max_student = max(students.items(), key=lambda x: x[1])
print(max_student) # ('Palak', 92)
2. Syntax:
python
If you want, I can now solve Problem 4 (students dictionary) using lambda step by step so you see it
applied.
Do you want me to do that?
ok
Perfect! Let’s solve Problem 4 – Students dictionary using lambda step by step.
Problem Recap
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 60/122
python
students = {'Nishit': 85, 'Palak': 92, 'Rohan': 78, 'Sneha': 92, 'Amit': 70}
Tasks:
python
Output:
css
Explanation:
python
Output:
csharp
Sorted Students by Score: {'Palak': 92, 'Sneha': 92, 'Nishit': 85, 'Rohan': 78, 'Amit': 70}
Explanation:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 61/122
reverse=True → descending order
✅ Key Takeaways
1. lambda x: x[1] → commonly used for sorting dict by value.
2. filter(lambda x: condition, iterable) → select elements based on condition.
3. max() + lambda → easily find max value with corresponding key.
If you want, we can now move to Problem 5 – OOP + Python coding, like creating a class with
methods, inheritance, and encapsulation which is very likely in Xalt Analytics interviews.
Do you want to do that next?
ok
Question:
Create a Student class with the following:
python
class Student:
def __init__(self, name, roll_no, marks):
self.name = name
self.roll_no = roll_no
self.__marks = marks # private variable
def average_marks(self):
return sum(self.__marks.values()) / len(self.__marks)
def top_subject(self):
return max(self.__marks, key=self.__marks.get) # subject with max marks
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 62/122
def get_marks(self):
return self.__marks
python
Output:
yaml
🔹 Explanation
1. self.__marks → private attribute (encapsulation).
2. average_marks() → sum all marks / number of subjects.
3. top_subject() → max(dict, key=dict.get) → finds key with highest value.
4. Two students are created → demonstrates objects and method usage.
💡 Interview Tip:
You can be asked slightly modified scenarios:
Add a method to update marks.
Inherit from a Person class with name and roll_no.
Always mention time complexity if looping through marks → O(n).
If you want, we can now do Problem 6 – Combined DSA + Python (like rotate array, reverse string, or
find duplicates) as a final practice for your interview.
Do you want to do that next?
ok
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 63/122
Perfect! 🚀
Let’s do Problem 6 – Combined DSA + Python. This will simulate a typical interview coding
question.
Question:
Given an array of integers:
python
arr = [1, 2, 3, 4, 5, 3, 2, 6]
Tasks:
Example Output:
vbnet
Input: [1, 2, 3, 4, 5, 3, 2, 6]
Step1: Remove duplicates → [1, 2, 3, 4, 5, 6]
Step2: Rotate right by 3 → [4, 5, 6, 1, 2, 3]
python
arr = [1, 2, 3, 4, 5, 3, 2, 6]
seen = set()
unique_arr = []
for num in arr:
if num not in seen:
unique_arr.append(num)
seen.add(num)
Output:
less
python
k = 3
n = len(unique_arr)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 64/122
k = k % n # handle k > n
Output:
less
🔹 Explanation
1. seen → keeps track of numbers already added → removes duplicates.
2. unique_arr[-k:] + unique_arr[:-k] → rotates array to the right by k.
✅ Interview Tips
Always clarify left or right rotation.
For duplicates:
Use set + list for maintaining order.
Avoid nested loops → O(n² time).
Mention time complexity:
Remove duplicates → O(n)
Rotate → O(n)
Total → O(n)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 65/122
no i just have today and tomorrow
Got it! ⏱Since you have only 2 days, we need a focused, high-yield revision plan to maximize your
prep for Xalt Analytics. I’ll break it down hour by hour with priorities.
Arrays / Lists:
Reverse array, rotate array, remove duplicates
Find missing numbers, move zeros
Strings:
Reverse words, anagrams, first non-repeating character
Practice 1–2 easy + 1 medium problems from above
Tips:
Dictionary operations:
Count frequencies, max value key, sort by values
Lambda:
Sorting dict, filtering, max/min with key
Quick practice: 3–4 problems combining dict + lambda
Tips:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 66/122
Focus on:
Private & protected variables (_ and __)
Method overriding and super()
🔹 Extra Tips
1. Explain as you code – Interviewers love reasoning.
2. Write clean code – Use functions, meaningful variable names.
3. Focus on common patterns – rotate arrays, reverse strings, dict operations, OOP scenarios.
4. Stay calm & confident – If stuck, explain your thought process clearly.
If you want, I can make a super condensed 1–2 hour “last-minute key points cheat sheet” for Python,
DSA, OOP, Lambda, and Pandas that you can quickly revise today and tomorrow.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 67/122
Do you want me to make that cheat sheet?
ok
Perfect! 🚀
Here’s your 2-day last-minute cheat sheet for Python, DSA, OOP, Lambda, and Pandas. You
can quickly revise this today and tomorrow.
Reverse: arr[::-1]
Rotate right by k: arr[-k:] + arr[:-k]
Remove duplicates while maintaining order:
python
seen = set()
unique = [x for x in arr if not (x in seen or seen.add(x))]
python
Strings
python
python
for i, c in enumerate(s):
if s.count(c) == 1:
return i
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
Dictionaries
Count frequency:
python
freq = {}
for x in arr:
freq[x] = freq.get(x,0)+1
python
python
🔹 Lambda Functions
Syntax: lambda arguments: expression
Examples:
python
# Square numbers
squared = list(map(lambda x: x**2, nums))
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 69/122
Protected: _var → can access, by convention should not
Class method: @classmethod def f(cls) → access class variables
Static method: @staticmethod def f() → utility function
Inheritance:
python
class Child(Parent):
def __init__(self):
super().__init__()
🔹 Pandas
Create DataFrame: df = pd.DataFrame(data)
Access columns: df['col']
Filter rows: df[df['col']>value]
Add column: df['new'] = df['col']*1.1
Apply function: df['col'].apply(lambda x: x*2)
Group by & aggregate: df.groupby('Department')['Salary'].mean()
Top N by group:
python
df[df['Salary'] == df.groupby('Department')['Salary'].transform('max')]
If you want, I can also make a super quick “15-min last-minute drill” with 5 must-practice problems
that cover everything above, so you can cram efficiently today.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 70/122
Do you want me to do that?
lets start revision day 1 morning core python basics and dsa
python
arr = [1, 2, 3, 4]
rev = arr[::-1] # [4, 3, 2, 1]
Rotate array
Right rotation by k:
python
arr = [1,2,3,4,5]
k = 2
rot = arr[-k:] + arr[:-k] # [4,5,1,2,3]
Left rotation by k:
python
python
arr = [1,2,3,2,1,4]
seen = set()
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 71/122
unique = [x for x in arr if not (x in seen or seen.add(x))]
print(unique) # [1,2,3,4]
python
arr = [1,2,4,5]
n = 5
missing = (n*(n+1))//2 - sum(arr)
print(missing) # 3
python
arr = [0,1,0,3,12]
arr = [x for x in arr if x != 0] + [0]*(arr.count(0))
print(arr) # [1,3,12,0,0]
2️⃣ Strings
Reverse words in string
python
python
s1 = "listen"
s2 = "silent"
print(sorted(s1.replace(" ","").lower()) == sorted(s2.replace(" ","").lower())) # True
python
s = "leetcode"
seen = {}
for c in s:
seen[c] = seen.get(c,0)+1
for i, c in enumerate(s):
if seen[c] == 1:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 72/122
print(i) # 0
break
python
strs = ["flower","flow","flight"]
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
print(prefix) # "fl"
Once you solve these 5 problems, I’ll review your solutions and move to Strings + Dictionary +
Lambda, which is next part of the morning session.
Do you want to solve the 5 problems now one by one?
ok good but can you give me 2 version like 1st one is without prebuild function and than 2nd
with prebuild function ok
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 73/122
Problem 1 – Reverse an array
Input: [1, 2, 3, 4]
python
arr = [1, 2, 3, 4]
rev = []
for i in range(len(arr)-1, -1, -1):
rev.append(arr[i])
print(rev) # [4, 3, 2, 1]
python
arr = [1, 2, 3, 4]
rev = arr[::-1] # slicing
# OR
arr.reverse() # in-place
rev = arr
print(rev) # [4, 3, 2, 1]
python
arr = [1,2,3,4,5,6]
k = 3
rot = []
for i in range(len(arr)):
rot.append(arr[(i+k)%len(arr)])
print(rot) # [4,5,6,1,2,3]
python
arr = [1,2,3,4,5,6]
k = 3
rot = arr[k:] + arr[:k]
print(rot) # [4,5,6,1,2,3]
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 74/122
Version 1 – Without pre-built function
python
arr = [1,2,4,5,6]
n = 6
expected_sum = 0
for i in range(1, n+1):
expected_sum += i
actual_sum = 0
for x in arr:
actual_sum += x
missing = expected_sum - actual_sum
print(missing) # 3
python
arr = [1,2,4,5,6]
n = 6
missing = (n*(n+1))//2 - sum(arr)
print(missing) # 3
python
arr = [1,2,2,3,4,1,5]
unique = []
seen = {}
for x in arr:
if x not in seen:
unique.append(x)
seen[x] = True
print(unique) # [1,2,3,4,5]
python
arr = [1,2,2,3,4,1,5]
unique = list(dict.fromkeys(arr))
print(unique) # [1,2,3,4,5]
python
s = "aabbcdde"
for i in range(len(s)):
count = 0
for j in s:
if s[i] == j:
count += 1
if count == 1:
print(i, s[i])
break
python
s = "aabbcdde"
from collections import Counter
freq = Counter(s)
for i, c in enumerate(s):
if freq[c] == 1:
print(i, c)
break
✅ Done! You now have two versions for all 5 core problems: manual logic and pre-built Python
shortcuts.
If you want, we can move to Day 1 Morning – Strings + Dictionary + Lambda next, with two versions
for each problem as well.
Do you want to continue with that?
Absolutely! 😎Let’s expand your Day 1 Morning – Core Python + DSA with more practice problems. I’ll
give you both versions (without pre-built and with Python shortcuts) for each.
These problems are common in coding interviews.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 76/122
python
arr = [1, 2, 2, 3, 3, 3, 4]
freq = {}
for x in arr:
if x in freq:
freq[x] += 1
else:
freq[x] = 1
duplicates = {}
for key, val in freq.items():
if val > 1:
duplicates[key] = val
print(duplicates) # {2: 2, 3: 3}
python
python
arr = [1,2,3,2,1]
is_palindrome = True
for i in range(len(arr)//2):
if arr[i] != arr[-(i+1)]:
is_palindrome = False
break
print(is_palindrome) # True
python
arr = [1,2,3,2,1]
print(arr == arr[::-1]) # True
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 77/122
Version 1 – Without pre-built function
python
arr = [1,-2,3,-4,5]
negatives = []
positives = []
for x in arr:
if x < 0:
negatives.append(x)
else:
positives.append(x)
arr = negatives + positives
print(arr) # [-2,-4,1,3,5]
python
arr = [1,-2,3,-4,5]
arr.sort(key=lambda x: x>=0)
print(arr) # [-2,-4,1,3,5]
python
arr = [10,20,4,45,99]
first = second = float('-inf')
for x in arr:
if x > first:
second = first
first = x
elif x > second and x != first:
second = x
print(second) # 45
python
arr = [10,20,4,45,99]
arr = list(set(arr))
arr.sort()
print(arr[-2]) # 45
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 78/122
Input: "Hello World"
Output: 3 (e, o, o)
python
s = "Hello World"
vowels = "aeiouAEIOU"
count = 0
for c in s:
if c in vowels:
count += 1
print(count) # 3
python
s = "Hello World"
count = sum(1 for c in s if c.lower() in 'aeiou')
print(count) # 3
✅ These 5 extra problems cover arrays, strings, and frequency-based logic – all very common in
interviews.
If you want, I can now prepare 10 more high-yield “strings + dict + lambda” problems for your
morning session so you can finish Day 1 Morning completely.
Do you want me to do that?
ok
Perfect 🔥 Let’s supercharge your Day 1 Morning Revision (Core Python + DSA).
I’ll give you 10 high-yield problems (string + dict + lambda) with two versions each (manual +
Pythonic).
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 79/122
python
python
python
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 80/122
python
s = "programming"
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
print(freq) # {'p':1, 'r':2, 'o':1, 'g':2, ...}
python
python
s = "aabbcdde"
for i in range(len(s)):
if s.count(s[i]) == 1:
print(s[i]) # c
break
python
python
s = "Hello World"
vowels = "aeiouAEIOU"
res = ""
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 81/122
for c in s:
if c not in vowels:
res += c
print(res) # Hll Wrld
python
s = "Hello World"
print("".join([c for c in s if c.lower() not in "aeiou"]))
python
python
python
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 82/122
python
python
arr = [1,2,3,4]
squares = []
for x in arr:
squares.append(x*x)
print(squares)
python
arr = [1,2,3,4]
print(list(map(lambda x: x*x, arr)))
python
arr = [1,2,3,4,5,6]
evens = []
for x in arr:
if x % 2 == 0:
evens.append(x)
print(evens)
python
arr = [1,2,3,4,5,6]
print(list(filter(lambda x: x%2==0, arr)))
python
python
✅ These 10 problems (11–20) now give you 20 practice problems total (arrays, strings, dict, lambda).
This covers 90% of Python coding interview basics.
Do you want me to now prepare a “DSA quick crash sheet” (stacks, queues, linked lists, sorting,
searching) in the same 2-version style for your afternoon revision?
ok
python
class Stack:
def __init__(self):
self.items = []
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 84/122
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
return "Stack is empty"
def peek(self):
if not self.is_empty():
return self.items[-1]
return "Stack is empty"
def is_empty(self):
return len(self.items) == 0
s = Stack()
s.push(10)
s.push(20)
print(s.peek()) # 20
print(s.pop()) # 20
python
stack = deque()
stack.append(10)
stack.append(20)
print(stack[-1]) # peek -> 20
print(stack.pop()) # pop -> 20
python
class Queue:
def __init__(self):
self.items = []
def dequeue(self):
if not self.is_empty():
return self.items.pop(0)
return "Queue is empty"
def is_empty(self):
return len(self.items) == 0
q = Queue()
q.enqueue(1)
q.enqueue(2)
print(q.dequeue()) # 1
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 85/122
python
queue = deque()
queue.append(1) # enqueue
queue.append(2)
print(queue.popleft()) # dequeue -> 1
python
class Node:
def __init__(self, data):
self.data = data
self.next = None
def reverse(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
python
arr = [1,2,3,4,5]
print(arr[::-1]) # simulate reversed linked list
python
print(binary_search([1,2,3,4,5], 4)) # 3
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 86/122
Version 2 – Using bisect
python
import bisect
arr = [1,2,3,4,5]
idx = bisect.bisect_left(arr, 4)
print(idx if idx < len(arr) and arr[idx] == 4 else -1) # 3
python
arr = [5,1,4,2,8]
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]
print(arr) # [1,2,4,5,8]
python
arr = [5,1,4,2,8]
print(sorted(arr)) # [1,2,4,5,8]
python
arr = [3,2,1,5,6,4]
k = 2
arr.sort()
print(arr[-k]) # 5
python
import heapq
arr = [3,2,1,5,6,4]
k = 2
print(heapq.nlargest(k, arr)[-1]) # 5
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 87/122
Problem 27 – Valid Parentheses (Stack problem)
Version 1 – Manual
python
def is_valid(s):
stack = []
pairs = {')':'(', '}':'{', ']':'['}
for char in s:
if char in pairs.values():
stack.append(char)
elif char in pairs:
if not stack or stack.pop() != pairs[char]:
return False
return not stack
print(is_valid("()[]{}")) # True
python
s = "()[]{}"
while "()" in s or "{}" in s or "[]" in s:
s = s.replace("()", "").replace("{}", "").replace("[]", "")
print(s == "") # True
python
def find_peak(arr):
left, right = 0, len(arr)-1
while left < right:
mid = (left+right)//2
if arr[mid] < arr[mid+1]:
left = mid+1
else:
right = mid
return arr[left]
print(find_peak([1,2,3,1])) # 3
python
arr = [1,2,3,1]
print(max(arr)) # 3
Do you want me to now make a Day 2 (SQL + Pandas + Case Studies) crash prep in the same style
(manual + shortcut)?
Yes👍 let’s go through some more important DSA practice problems in Python (both without
prebuilt functions and with prebuilt functions wherever possible).
1. Reverse a String
python
def reverse_string(s):
rev = ""
for char in s:
rev = char + rev
return rev
print(reverse_string("hello"))
python
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
python
def is_palindrome(s):
s = s.lower()
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome("madam"))
print(is_palindrome("hello"))
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 89/122
With prebuilt function
python
def is_palindrome(s):
return s.lower() == s[::-1].lower()
print(is_palindrome("madam"))
print(is_palindrome("hello"))
python
def find_max_min(arr):
max_val = arr[0]
min_val = arr[0]
for num in arr:
if num > max_val:
max_val = num
if num < min_val:
min_val = num
return max_val, min_val
print(find_max_min([4, 2, 9, 1, 7]))
python
def find_max_min(arr):
return max(arr), min(arr)
print(find_max_min([4, 2, 9, 1, 7]))
python
def first_repeated_char(s):
seen = []
for char in s:
if char in seen:
return char
seen.append(char)
return None
print(first_repeated_char("programming"))
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 90/122
python
def first_repeated_char(s):
seen = set()
for char in s:
if char in seen:
return char
seen.add(char)
return None
print(first_repeated_char("programming"))
python
print(rotate_array([1,2,3,4,5], 2))
python
print(rotate_array([1,2,3,4,5], 2))
👉 These are commonly asked in coding interviews for core Python & DSA basics.
Do you want me to prepare a full set of 20+ DSA revision problems (like arrays, strings, stacks, queues,
searching, sorting) for your 2-day revision plan?
ok
Perfect 👍
Let’s set up a DSA revision plan for your Day 1 & Day 2.
We’ll do 20+ problems (array, string, searching, sorting, stack, queue, hashing) — with both manual
logic and prebuilt function versions.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 91/122
🔹 Day 1 – Core Python Basics + DSA (Arrays & Strings)
1. Reverse a string
2. Check palindrome string
3. Find max & min in an array
4. Find 2nd largest element
5. Count frequency of characters in string
6. Find first non-repeating character
7. Find first repeated character
8. Rotate an array (left/right)
9. Missing number in 1…n series
10. Remove duplicates from array/string
ok
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 92/122
Perfect 👍 Let’s start with Day 1 (Problems 1–10).
I’ll give you two versions for each problem:
print(reverse_string("python")) # nohtyp
print(reverse_string_builtin("python")) # nohtyp
print(is_palindrome("madam")) # True
# (2) Prebuilt
def is_palindrome_builtin(s):
return s.lower() == s[::-1].lower()
print(is_palindrome_builtin("Madam")) # True
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 93/122
def find_min_max(arr):
mn, mx = arr[0], arr[0]
for num in arr:
if num < mn:
mn = num
if num > mx:
mx = num
return mn, mx
# (2) Prebuilt
print(min(arr), max(arr)) # (1, 89)
# (1) Manual
def second_largest(arr):
first = second = float('-inf')
for num in arr:
if num > first:
second = first
first = num
elif first > num > second:
second = num
return second
print(second_largest(arr)) # 45
# (2) Prebuilt
def second_largest_builtin(arr):
return sorted(set(arr))[-2]
print(second_largest_builtin(arr)) # 45
s = "programming"
# (1) Manual
def char_frequency(s):
freq = {}
for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
return freq
# (2) Prebuilt
from collections import Counter
print(dict(Counter(s)))
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 94/122
🔹 Problem 6: First Non-Repeating Character
python
s = "leetcode"
# (1) Manual
def first_non_repeat(s):
for ch in s:
if s.count(ch) == 1:
return ch
return None
print(first_non_repeat(s)) # l
print(first_non_repeat_builtin(s)) # l
s = "programming"
# (1) Manual
def first_repeated(s):
seen = set()
for ch in s:
if ch in seen:
return ch
seen.add(ch)
return None
print(first_repeated(s)) # r
print(first_repeated_builtin(s)) # r
arr = [1,2,3,4,5,6,7]
arr = [1,2,3,5]
n = 5
print(missing_number(arr, n)) # 4
print(missing_number_builtin(arr, n)) # 4
arr = [1,2,2,3,4,4,5]
# (1) Manual
def remove_duplicates(arr):
result = []
for num in arr:
if num not in result:
result.append(num)
return result
print(remove_duplicates(arr)) # [1,2,3,4,5]
# (2) Prebuilt
print(list(set(arr))) # [1,2,3,4,5] (order not guaranteed)
print(list(dict.fromkeys(arr))) # [1,2,3,4,5] (order preserved)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 96/122
✅ That covers Day 1 – Core Python + DSA basics (10 problems).
Do you want me to continue with Day 2 (problems 11–20) now, or should we first revise these 10 by
solving some yourself?
i have read this question are there more of them that i can practice before going to day 2
Yes✅ there are definitely more Day-1 level (arrays & strings) practice problems you can try before
moving to Day-2.
These are slightly different but still core basics — perfect for an interview warm-up.
⚡ My suggestion:
Before we go to Day-2 (Searching, Sorting, Stacks, Queues), you pick 5–6 of these extra problems, try
coding them yourself, and I’ll check & improve them with you.
Would you like me to start writing code + explanation for all 10 extra problems, or do you want to
pick a few and attempt first?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 97/122
ok
python
# (1) Manual
def reverse_words(sentence):
words = sentence.split()
rev = []
for i in range(len(words)-1, -1, -1):
rev.append(words[i])
return " ".join(rev)
# (2) Prebuilt
def reverse_words_builtin(sentence):
return " ".join(sentence.split()[::-1])
python
# (1) Manual
def is_anagram(s1, s2):
if len(s1) != len(s2):
return False
for ch in s1:
if s1.count(ch) != s2.count(ch):
return False
return True
# (2) Prebuilt
def is_anagram_builtin(s1, s2):
return sorted(s1) == sorted(s2)
python
import string
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 98/122
# (1) Manual
def is_pangram(s):
s = s.lower()
for ch in string.ascii_lowercase:
if ch not in s:
return False
return True
# (2) Prebuilt
def is_pangram_builtin(s):
return set(string.ascii_lowercase) <= set(s.lower())
python
# (1) Manual
def longest_word(sentence):
words = sentence.split()
longest = words[0]
for word in words:
if len(word) > len(longest):
longest = word
return longest
print(longest_word(sentence)) # programming
# (2) Prebuilt
print(max(sentence.split(), key=len)) # programming
python
arr = [1,2,3,2,4,2,5,1,3,3,3]
# (1) Manual
def most_frequent(arr):
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
max_count = 0
element = None
for k,v in freq.items():
if v > max_count:
max_count = v
element = k
return element
print(most_frequent(arr)) # 3
# (2) Prebuilt
from collections import Counter
print(Counter(arr).most_common(1)[0][0]) # 3
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 99/122
6. Check if array is sorted
python
# (1) Manual
def is_sorted(arr):
for i in range(1, len(arr)):
if arr[i] < arr[i-1]:
return False
return True
print(is_sorted([1,2,3,4,5])) # True
print(is_sorted([1,3,2,5])) # False
# (2) Prebuilt
def is_sorted_builtin(arr):
return arr == sorted(arr)
print(is_sorted_builtin([1,2,3,4,5])) # True
python
arr1 = [1,2,3,4,5]
arr2 = [4,5,6,7]
# (1) Manual
def common_elements(a, b):
result = []
for x in a:
if x in b and x not in result:
result.append(x)
return result
# (2) Prebuilt
print(list(set(arr1) & set(arr2))) # [4, 5]
python
# (1) Manual
def two_sum(arr, target):
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == target:
return (arr[i], arr[j])
return None
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 100/122
diff = target - num
if diff in seen:
return (diff, num)
seen[num] = i
return None
python
s = "abc"
# (1) Manual
def substrings(s):
result = []
for i in range(len(s)):
for j in range(i+1, len(s)+1):
result.append(s[i:j])
return result
print(substrings(s)) # ['a','ab','abc','b','bc','c']
python
s = "Hello World"
# (1) Manual
def count_vowels_consonants(s):
vowels = "aeiou"
v_count, c_count = 0, 0
for ch in s.lower():
if ch.isalpha():
if ch in vowels:
v_count += 1
else:
c_count += 1
return v_count, c_count
print(count_vowels_consonants(s)) # (3,7)
# (2) Prebuilt
import re
v_count = len(re.findall(r'[aeiou]', s.lower()))
c_count = len(re.findall(r'[bcdfghjklmnpqrstvwxyz]', s.lower()))
print(v_count, c_count) # (3,7)
✅ Now you have 20 full practice problems (10 Day-1 + 10 Extra) before Day-2.
👉 Do you want me to quiz you (I’ll ask a problem, you code it, then I correct), or should I move to Day-
2 advanced DSA (sorting, searching, stack/queue)?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 101/122
lets take a break and then we will continue ok
👉 We’ll do these step by step, with manual implementation first + then Python built-in way.
Shall I start with Problem 11: Binary Search?
ok
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 102/122
🔹 Problem 11: Binary Search
Definition
if arr[mid] == target:
return mid # return index
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
python
import bisect
👉 In interviews, they usually expect you to write the manual version first, but knowing bisect is a
bonus.
⚡ Do you want me to give you a practice question on binary search (like finding first occurrence, last
occurrence, or number of times element appears), or should I move to Problem 12: Sorting?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 103/122
ok
Python has Timsort (used in sort() and sorted()), which is highly optimized.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1): # last i elements already sorted
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j] # swap
return arr
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr)//2]
left = [x for x in arr if x < pivot]
mid = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + mid + quick_sort(right)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 104/122
Worst Case: O(n²) (if bad pivot chosen)
# Descending
print(sorted(arr, reverse=True)) # [64, 25, 22, 12, 11]
⚡ Would you like me to also show you sorting by custom conditions (like sorting students by
marks), or should we go straight to Problem 13: Merge two sorted arrays?
Perfect👍 Let’s cover Sorting by Custom Condition because interviewers often test this with
dictionaries, tuples, or objects.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __repr__(self):
return f"{self.name}({self.marks})"
# Sort by marks
print(sorted(students, key=lambda s: s.marks))
# [Bob(72), Alice(85), Charlie(90)]
🔑 Interview Tip:
If they ask you to sort without built-in sorted(), you can just implement Bubble/Quick sort and modify
the comparison condition.
👉 Do you want me to now give you a few custom sorting practice problems (like "sort employees by
salary, then by name") before moving to the next DSA problem?
ok
Input:
python
Expected Output:
css
Input:
python
Expected Output:
css
Input:
python
data = [(1, 3), (2, 3), (3, 2), (4, 5), (5, 5)]
Expected Output:
css
[(4, 5), (5, 5), (1, 3), (2, 3), (3, 2)]
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 107/122
Input:
python
Expected Output:
css
python
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __repr__(self):
return f"{self.name}({self.marks})"
Expected Output:
csharp
Do you want me to solve one as an example (both ways), and you try the rest?
python
print(words)
python
for i in range(len(employees)):
for j in range(len(employees)-1):
if employees[j][1] > employees[j+1][1] or (employees[j][1] == employees[j+1][1] and
employees[j][0] > employees[j+1][0]):
employees[j], employees[j+1] = employees[j+1], employees[j]
print(employees)
🔹 With sorted()
python
✅ Q3. Sort tuples by 2nd element (desc), then 1st element (asc)
🔹 Without prebuilt
python
data = [(1, 3), (2, 3), (3, 2), (4, 5), (5, 5)]
for i in range(len(data)):
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 109/122
for j in range(len(data)-1):
if data[j][1] < data[j+1][1] or (data[j][1] == data[j+1][1] and data[j][0] > data[j+1]
[0]):
data[j], data[j+1] = data[j+1], data[j]
print(data)
🔹 With sorted()
python
data = [(1, 3), (2, 3), (3, 2), (4, 5), (5, 5)]
print(sorted(data, key=lambda x: (-x[1], x[0])))
for i in range(len(items)):
for j in range(len(items)-1):
if items[j][1] < items[j+1][1] or (items[j][1] == items[j+1][1] and items[j][0] >
items[j+1][0]):
items[j], items[j+1] = items[j+1], items[j]
print(items)
🔹 With sorted()
python
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __repr__(self):
return f"{self.name}({self.marks})"
for i in range(len(students)):
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 110/122
for j in range(len(students)-1):
if students[j].marks > students[j+1].marks or (students[j].marks == students[j+1].marks
and students[j].name > students[j+1].name):
students[j], students[j+1] = students[j+1], students[j]
print(students)
🔹 With sorted()
python
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __repr__(self):
return f"{self.name}({self.marks})"
🔥 These cover manual sorting logic and Pythonic sorting with lambda.
Do you want me to now create a list of 10+ quick DSA sorting practice problems (mix of arrays,
strings, dicts) for revision?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 111/122
while i < len(arr1):
merged.append(arr1[i])
i += 1
return merged
✅ Output:
csharp
[1, 2, 3, 4, 5, 6]
✅ Output:
csharp
[1, 2, 3, 4, 5, 6]
ok next
def is_balanced(s):
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in "([{": # opening bracket
stack.append(char)
elif char in ")]}": # closing bracket
if not stack or stack[-1] != pairs[char]:
return False
stack.pop()
return len(stack) == 0
print(is_balanced("{[()]}")) # ✅
❌ True
print(is_balanced("{[(])}"))
print(is_balanced("((()))"))
#
# ✅ False
True
python
def is_balanced_deque(s):
stack = deque()
pairs = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in "([{":
stack.append(char)
elif char in ")]}":
if not stack or stack.pop() != pairs[char]:
return False
return not stack
print(is_balanced_deque("{[()]}")) # True
print(is_balanced_deque("{[(])}")) # False
👉 Do you want me to now give you a slight twist version of this (like checking HTML/XML tag
balancing)?
ok next
1. Using a list
2. Using Python’s collections.deque
class QueueList:
def __init__(self):
self.queue = []
def dequeue(self):
if self.queue:
return self.queue.pop(0) # remove from front
return "Queue is empty"
def peek(self):
return self.queue[0] if self.queue else "Queue is empty"
def is_empty(self):
return len(self.queue) == 0
q = QueueList()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
print(q.dequeue()) # 10
print(q.peek()) # 20
print(q.is_empty()) # False
python
class QueueDeque:
def __init__(self):
self.queue = deque()
def dequeue(self):
return self.queue.popleft() if self.queue else "Queue is empty"
def peek(self):
return self.queue[0] if self.queue else "Queue is empty"
def is_empty(self):
return len(self.queue) == 0
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 114/122
q = QueueDeque()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
print(q.dequeue()) # 10
print(q.peek()) # 20
print(q.is_empty()) # False
🔑 Interview Tip:
Always mention deque in interviews for efficient queue operations (O(1)).
Lists are okay for small examples, but pop(0) is slow for large data.
Do you want me to continue with Stack implementation next, or Majority Element / Subarray Sum
problems?
ok
1. Using a list
2. Using Python’s collections.deque
class StackList:
def __init__(self):
self.stack = []
def pop(self):
return self.stack.pop() if self.stack else "Stack is empty"
def peek(self):
return self.stack[-1] if self.stack else "Stack is empty"
def is_empty(self):
return len(self.stack) == 0
s = StackList()
s.push(10)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 115/122
s.push(20)
s.push(30)
print(s.pop()) # 30
print(s.peek()) # 20
print(s.is_empty())# False
python
class StackDeque:
def __init__(self):
self.stack = deque()
def pop(self):
return self.stack.pop() if self.stack else "Stack is empty"
def peek(self):
return self.stack[-1] if self.stack else "Stack is empty"
def is_empty(self):
return len(self.stack) == 0
s = StackDeque()
s.push(10)
s.push(20)
s.push(30)
print(s.pop()) # 30
print(s.peek()) # 20
print(s.is_empty())# False
🔑 Interview Tip:
Mention that list or deque can implement stack in Python.
append() → push, pop() → pop from top.
peek/top is stack[-1].
Next, we can move to Majority Element (Boyer-Moore Voting Algorithm) or Subarray with given
sum — both are very common interview questions.
Which one do you want to do next?
ok
Great ✅ Let’s do Majority Element (Boyer-Moore Voting Algorithm) next — very common in
interviews.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 116/122
✅ Problem: Majority Element
Definition:
Find the element in an array that appears more than n/2 times.
def majority_element(arr):
counts = {}
for num in arr:
counts[num] = counts.get(num, 0) + 1
if counts[num] > len(arr)//2:
return num
return None
arr = [3, 3, 4, 2, 3, 3, 3]
print(majority_element(arr)) # 3
def majority_element_boyer_moore(arr):
candidate = None
count = 0
arr = [3, 3, 4, 2, 3, 3, 3]
print(majority_element_boyer_moore(arr)) # 3
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 117/122
Boyer-Moore is optimal for large arrays.
Always verify candidate if not guaranteed majority.
Next, we can move to Subarray with Given Sum problem — very common for arrays and prefix sums.
Do you want to do that next?
ok
Perfect ✅ Let’s do Subarray with Given Sum next — another classic DSA problem.
✅ Problem: Subarray with Given Sum
Definition:
Given an array and a target sum, find a continuous subarray whose sum equals the target.
Example:
python
arr = [1, 2, 3, 7, 5]
target = 12
# Output: [2, 3, 7] or indices [1, 3]
arr = [1, 2, 3, 7, 5]
target = 12
print(subarray_sum_brute(arr, target)) # [2, 3, 7]
arr = [1, 2, 3, 7, 5]
target = 12
print(subarray_sum_hash(arr, target)) # [2, 3, 7]
🔑 Interview Tip:
Brute force is okay for small arrays.
For large arrays or repeated queries → use prefix sum + hash map.
Can also be solved with sliding window if all numbers are positive.
Binary Search
Sorting & Custom Sorting
Merge Two Sorted Arrays
Do you want me to summarize all Day-1 + Day-2 problems with key tips for interview prep next?
what is hash map and sliding window in python and then we summarize all problem
Time complexity:
Lookup: O(1) average
Insert: O(1) average
Example
python
# Add/update value
student_scores["David"] = 65
student_scores["Alice"] = 95
Usage in DSA:
Idea: Keep a window (start, end) and move it forward instead of recomputing sums or counts
from scratch.
Time complexity: O(n)
python
arr = [1, 2, 3, 4, 5]
k = 3
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 120/122
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(len(arr)-k):
window_sum = window_sum - arr[i] + arr[i+k] # slide window
max_sum = max(max_sum, window_sum)
print(max_sum) # 12 (3+4+5)
Usage in DSA:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 121/122
5. Sorting: Manual for small examples, sorted() + lambda for custom sorting.
6. Practice arrays + strings — they cover 70% of coding questions.
If you want, I can now make a Day-3 plan for your final interview prep, which will include Python OOP,
Lambda, Pandas, SQL, and tricky problems — basically everything Xalt Analytics might ask.
Do you want me to do that next?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 122/122