0% found this document useful (0 votes)
41 views122 pages

? Step 1 - Python Programming & Scripting

Uploaded by

dekunj007
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)
41 views122 pages

? Step 1 - Python Programming & Scripting

Uploaded by

dekunj007
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
You are on page 1/ 122

Q. Which join operation will result in the largest number of rows?

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

Your current answer is not correct — let me clarify properly.

📌 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.

If Table A has 10 rows and Table B has 8 rows,


→ CROSS JOIN will produce 10 × 8 = 80 rows.

About Other Joins:

INNER JOIN → returns only matching rows.

LEFT/RIGHT OUTER JOIN → returns all rows from one table plus matching rows from the other.

FULL OUTER JOIN → returns all rows from both tables.

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:

Product Life Cycle: Introduction → Growth → Maturity → Decline.


Software Life Cycle: Requirement Analysis → Design → Development → Testing →
Deployment → Maintenance.

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:

PLC: Marketing, sales strategy, customer behavior, product profitability.

SDLC: Developers, testers, project managers, system analysts, user feedback.

👉 In short:
Product Life Cycle = market journey of a product.

Software Life Cycle = technical journey of software development.

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.

Do practice coding questions on platforms like LeetCode / GeeksforGeeks / HackerRank.

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.

Be able to write clean, efficient code for problems.

3. SQL
Many companies ask SQL queries along with coding.

Revise SELECT, WHERE, GROUP BY, HAVING, ORDER BY, JOINS, subqueries, aggregate
functions.

Be ready for queries like:

Find 2nd highest salary.


Count employees in each department.

Get customers who bought more than X items.

✅ Strategy for Next 2 Days


Saturday (Tomorrow):
Morning → DSA (arrays, strings, recursion).

Afternoon → SQL practice.


Evening → Python coding (LeetCode easy-medium).
Sunday:

Morning → DSA (linked list, stack, queue, trees).


Afternoon → SQL advanced queries + practice.

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.

Practice 2 easy-medium problems in Python for warm-up.

👉 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.

🔍 What We Know About Xalt Analytics


Here’s what their domain, services, and tech focus suggest about what they’ll likely test:

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

So your interview might check:

Programming / coding (likely in Python)


Data Structures & Algorithms

SQL / data querying


Basic statistics, data handling, maybe ML/NLP basics

Projects or portfolio questions (what you’ve done, challenges)


Possibly scenario questions: how to solve a data problem end-to-end

🛠 Key Topics to Cover (Tailored to Xalt)


Here’s what you should absolutely master before Monday:

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

They will expect you to code


Python programming List / dict ops, comprehensions, file I/O,
solutions, manipulate data, maybe
& scripting exceptions, classes, libraries (NumPy, Pandas)
build pipelines
Arrays, strings, hashing, two-pointers, recursion,
Data Structures &
To test your problem-solving ability sorting, searching, trees, heaps, basic dynamic
Algorithms (DSA)
programming
Analytics work often involves Joins, subqueries, GROUP BY, HAVING, window
SQL & Data querying
querying relational data functions, aggregations, optimization
Basic statistics & To reason about data, Mean, median, variance, probability, correlation,
probability distributions, hypothesis maybe basic hypothesis testing
Machine Learning / Since they do AI/ML & data Regression, classification, clustering, overfitting
Data Science basics products vs underfitting, feature engineering
Tokenization, stopwords, TF-IDF, embeddings,
NLP / Text analytics They explicitly do text /
sentiment analysis, basics of transformer / LLM
basics unstructured data work
ideas
Projects / past work / They’ll ask about your projects & Be ready to explain your role, challenges, data
case scenarios problem-solving approach pipeline, model evaluation, trade-offs

🎯 Mock Questions / Practice (For Xalt-style)


Here are sample questions you should practice (coding + theory):

Coding / DSA

1. Two-sum / Pair sum


Given an array, find two numbers that sum to a target.
2. Longest substring without repeating characters
“Given a string, find the length of the longest substring with no repeated characters.”
3. Merge intervals
Given intervals, merge overlapping intervals.

4. Tree traversal / Binary tree questions


Preorder / inorder / postorder, also depth / height.
5. Kth largest / smallest element
Using heap or quickselect.

6. Sliding window problems


Eg: maximum sum subarray of size k, or number of subarrays with sum ≤ X.

SQL / Data Questions

7. Second highest salary


“Write a query to get the 2nd highest salary from Employee table.”
8. Department-wise count
“Count number of employees in each department whose salary > 50000.”

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

11. When will you choose logistic regression vs decision tree?

12. How would you detect outliers in a dataset?


13. Text analytics scenario
“Given a collection of customer reviews (text), how to find top 5 positive and negative features
(aspects) for a product?”
14. Data pipeline design
“If you have raw log files from multiple sources, how will you design a pipeline to clean, join, and
visualize them?”
15. Model evaluation & metrics
“How do you evaluate a classification model? What metrics? What if classes are imbalanced?”

📅 2-Day Plan (From Now Until Monday)


Here’s how to systematically prepare:

Time Day Before (Sunday) Monday Morning / early

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:

Write out explanations in words (not just code).

Practice explaining your past projects clearly (problem, approach, challenges, results).

Do mock interviews (ask a friend or record yourself).


Brush up on basics (time complexity, space complexity).

🧠 Tips for the Day of Interview


Ask clarifying questions before starting any coding problem.
Think aloud — interviewers like to see your thought process.

Start with a brute-force solution, then optimize.

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)

4. Basic Statistics & Probability (mean/median, variance, correlation, probability basics)


5. Machine Learning / Data Science Basics (regression, classification, overfitting, feature engineering)

6. NLP / Text Analytics Basics (tokenization, TF-IDF, embeddings, sentiment analysis, transformers
overview)
7. Project & Case Study Prep (your resume projects + scenario-based Qs)

👉 Question for you before we start:


Do you want me to go in the same order (Python first → DSA → SQL → etc.) or should I prioritize the
most asked topics first (DSA + SQL + Python coding) and then cover ML/NLP/stats?

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.

📌 Step 1: Python Programming & Scripting


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/122
🔹 Core Concepts to Revise
1. Data Types & Operations

int, float, str, bool, list, tuple, set, dict


Example:

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}"

print(greet("Nishit")) # Hello Nishit

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")

6. Useful Libraries (just basics)

NumPy → numerical ops

Pandas → dataframes, analysis

python

import pandas as pd

data = {"Name": ["A", "B"], "Marks": [85, 90]}


df = pd.DataFrame(data)
print(df)

🔹 Mini Practice Questions


1. Write a function in Python to reverse a string.

2. Write code to count frequency of words in a sentence.


3. Create a class Employee with attributes name, salary, and a method to display info.

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?

lets discus in deep i have 3 days so lets study in deep ok

Perfect ✅ 3 days is enough if we go deep + structured.


We’ll break it down into study blocks, covering theory + examples + practice. I’ll teach as if we’re doing a
bootcamp together.

📌 Day 1 (Today) Plan – Python Deep Dive


We’ll cover in detail:

1. Python Basics (types, operators, loops, functions)

2. Collections (list, tuple, set, dict)

3. OOP (class, inheritance, polymorphism, encapsulation)


4. Exception Handling

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/122
5. File Handling

6. Modules & Libraries (NumPy, Pandas basics)

🔹 1. Python Basics
Variables & Data Types

Dynamic typing → You don’t declare types explicitly.

python

x = 10 # int
x = "Hello" # str

Built-in types: int, float, str, bool, None, list, tuple, set, dict

Operators

Arithmetic: + - * / // % **

Comparison: == != < > <= >=


Logical: and or not

Membership: in, not in

Identity: is, is not

👉 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

Ordered, mutable, allows duplicates

Methods: append, extend, insert, remove, pop, sort, reverse

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

Unordered, unique elements only

python

s = {1, 2, 2, 3}
print(s) # {1, 2, 3}

Dictionary

Key-value pairs, unordered

python

student = {"name": "Nishit", "age": 22}


print(student["name"]) # Nishit
student["marks"] = 95

🔹 3. Functions
Normal Function

python

def add(a, b):


return a + b
print(add(5, 3)) # 8

Default & Keyword Args

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

Using _protected and __private members.

Polymorphism

Same method, different behavior.

🔹 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

with open("data.txt", "w") as f:


f.write("Hello World")

with open("data.txt", "r") as f:


print(f.read())

🔹 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())

📌 That’s the Python foundation.


Tomorrow we’ll do DSA in Python (arrays, strings, recursion, trees, etc.).
👉 Do you want me to now create practice questions (with increasing difficulty) for Python only, so
you test your basics before we move to DSA?

ok but for now give me more detailed explanation on these topics

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.

1️⃣ Python Basics – Deep Dive


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/122
Variables & Data Types

Dynamic Typing: Python determines type automatically.

python

x = 10 # int
x = "Hello" # str (reassigned)

Immutable types: int, float, str, tuple → cannot change in place.


Mutable types: list, dict, set → can be modified.

Edge cases / tips:

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: ==, !=, <, >, <=, >=

Logical: and, or, not


Membership: in, not in → useful in interview questions
Identity: is, is not → checks memory location

Example edge case:

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

Loops: for, while, break, continue, else in loops

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

2️⃣ Collections – Deep Dive


List

Ordered, mutable, allows duplicates

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

Useful as dictionary keys or returning multiple values from functions.


Single element tuple:

python

t = (5,) # comma is necessary

Set

Unordered, unique, mutable


Useful for removing duplicates, set operations

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

Key-value, mutable, unordered (Python 3.7+ preserves insertion order)


Methods:

python

d = {"name":"Nishit", "age":22}
d.keys()
d.values()
d.items()
d.get("name") # safer than d["name"]
d.pop("age")

Interview tip: Be familiar with dict comprehension:

python

squares = {x: x*x for x in range(5)}

3️⃣ Functions – Deep Dive


Basics

python

def add(a, b):


return a + b

Default Arguments

python

def greet(name="Guest"):
print(f"Hello {name}")
greet()
greet("Nishit")

Keyword Arguments

python

def info(name, age):


print(name, age)
info(age=22, name="Nishit") # order can be swapped

Variable Arguments

*args → tuple of positional arguments


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/122
**kwargs → dictionary of keyword arguments

python

def demo(*args, **kwargs):


print(args)
print(kwargs)
demo(1,2,3, x=10, y=20)

Lambda Functions

Anonymous one-line functions

python

square = lambda x: x*x


print(square(5)) # 25

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

Interview tip: These are commonly asked in coding rounds for list/array manipulation.

4️⃣ OOP – Deep Dive


Class & Object

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

Same method name, different behavior (method overriding)

python

class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
for animal in [Dog(), Cat()]:
animal.sound() # Bark, Meow

5️⃣ Exception Handling – Deep Dive


Catch multiple exceptions

python

try:
a = int("abc")
except ValueError:
print("Value error")
except Exception as e:
print("Other error", e)
finally:
print("Done")

Raise your own exceptions

python

def check_age(age):
if age < 18:
raise ValueError("Too young")
check_age(15) # ValueError

6️⃣ File Handling – Deep Dive


python

# 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())

# Reading line by line


with open("file.txt") as f:
for line in f:
print(line.strip())

Interview tip: Understand difference between modes: r, w, a, r+, w+, a+

7️⃣ Libraries – Deep Dive


NumPy

Efficient numerical arrays, vectorized operations

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

DataFrames, series, indexing

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())

Interview tip: Know filtering rows, selecting columns, groupby, merge/join.

✅ 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

Use _protected (convention) or __private (name mangling) to restrict access

Variable Arguments

*args → tuple of positional arguments

**kwargs → dictionary of keyword arguments

Interview tip: Be familiar with dict comprehension:

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.

1️⃣ File Modes in Python (r, w, a, r+, w+, a+)


When you open a file in Python, the mode decides how you can interact with the file.

Mode Meaning Behavior


r read Open for reading. File must exist, error if not.
w write Open for writing. Creates file if not exists, overwrites if exists.

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.

a+ append/read Open for reading & appending. Creates if not exists.

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:

r → only read, error if file missing.


w → overwrites file.

a → appends without deleting existing content.


+ → allows both reading and writing.

2️⃣ Encapsulation in Python


Encapsulation = restricting access to internal details of a class so the outside code can’t mess with it.

Convention: _protected → means “don’t touch this” (not enforced)


Private: __private → Python name-mangles it to prevent accidental access

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:

Use encapsulation to hide sensitive data or internal logic.


Private variables can only be accessed inside the class or with name mangling.

3️⃣ Variable Arguments ( *args and **kwargs)


Python functions can take variable number of arguments.

*args

Collects positional arguments as a tuple.

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

Collects keyword arguments as a dictionary.

python

def student_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

student_info(name="Nishit", age=22, grade="A")


# Output:
# name: Nishit
# age: 22
# grade: A

Combining *args & **kwargs:

python

def demo(*args, **kwargs):


print("Args:", args)
print("Kwargs:", kwargs)

demo(1,2,3, x=10, y=20)


# Args: (1,2,3)
# Kwargs: {'x':10, 'y':20}

Interview Tip:

*args = flexible number of positional arguments


**kwargs = flexible number of named arguments

4️⃣ Dictionary Comprehension


Like list comprehension, but creates dictionaries.
Basic syntax:

python

{key_expr: value_expr for item in iterable if condition}

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}

# Only even numbers


even_squares = {x: x*x for x in range(5) if x%2==0}
print(even_squares) # {0:0, 2:4, 4:16}

# From two lists


keys = ["a","b","c"]
values = [1,2,3]
d = {k:v for k,v in zip(keys, values)}
print(d) # {'a':1, 'b':2, 'c':3}

Interview Tip:

Dictionary comprehension is very concise and Pythonic.


Often asked in coding rounds for mapping, counting frequency, or creating lookup tables.

✅ Summary of Key Points


Topic Key Points
File Modes r=read, w=overwrite, a=append, + allows both read/write
Encapsulation _protected = convention, __private = name mangling
*args Collect positional args as tuple
**kwargs Collect keyword args as dict

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.

🔹 Python Practice Problems (Step 1: Arrays & Strings)


Q1. Reverse an array without using built-in reverse()

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]

Q2. Find the maximum and minimum element in an array

python

def find_min_max(arr):
return min(arr), max(arr)

print(find_min_max([4,7,1,9,3])) # (1, 9)

Q3. Check if a string is a palindrome

python

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

print(is_palindrome("madam")) # True
print(is_palindrome("nishit")) # False

Q4. Count frequency of characters in a string

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}

Q5. Remove duplicates from an array

python

def remove_duplicates(arr):
return list(set(arr))

print(remove_duplicates([1,2,2,3,4,4,5])) # [1,2,3,4,5]

🔹 Step 2: Dictionaries & Lambda


Q6. Sort a dictionary by values
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/122
python

d = {"a": 3, "b": 1, "c": 2}


sorted_d = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted_d) # {'b':1, 'c':2, 'a':3}

Q7. Find the word with maximum length in a list

python

words = ["apple", "banana", "kiwi", "strawberry"]


longest = max(words, key=lambda x: len(x))
print(longest) # strawberry

🔹 Step 3: OOP Basics


Q8. Create a class Car with attributes and a method

python

class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def display(self):
return f"{self.brand} {self.model}"

c = Car("Tesla", "Model S")


print(c.display()) # Tesla Model S

🔹 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)

print(df) # show table


print(df["Age"].mean()) # average age
print(df[df["Score"] > 80]) # filter rows

✅ 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

Great! 🔥 Let’s start with 10 array + string practice problems.


I’ll give you the problem, a short hint, and then you try solving. If you get stuck, I’ll show the solution
step by step.

📝 Array + String Practice Problems


Q1. Reverse words in a string

Input: "I love Python"


Output: "Python love I"
Hint: Use split(), reverse the list, and join back.

Q2. Find the second largest element in an array

Input: [10, 20, 4, 45, 99]


Output: 45
Hint: Use sorted(set(arr)).

Q3. Check if two strings are anagrams

Input: "listen", "silent"


Output: True
Hint: Sort both and compare, or use frequency count.

Q4. Find duplicate characters in a string

Input: "programming"
Output: {'r': 2, 'g': 2, 'm': 2}

Q5. Find missing number in an array (1 to N)

Input: [1,2,3,5] (N=5)


Output: 4
Hint: Use formula n*(n+1)//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]

Q7. Check if a string has all unique characters

Input: "abcdef" → True, "hello" → False

Q8. Find first non-repeating character in a string

Input: "swiss"
Output: "w"

Q9. Rotate an array by k steps

Input: [1,2,3,4,5,6,7], k=3


Output: [5,6,7,1,2,3,4]
Hint: Use slicing.

Q10. Longest common prefix among strings

Input: ["flower","flow","flight"]
Output: "fl"

⚡ These 10 cover 90% of array/string interview questions.


👉 Do you want me to give you solutions step by step for each one, or do you want to try coding them
first and then I’ll check?

def reverse_string(s):
rev = []
s = s.split()
for word in s[::-1]:
rev.append(word[::-1])

return' '.join(rev)

print(reverse_string("I love Python"))

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"

print(reverse_string("I love Python"))

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)

print(reverse_string("I love Python"))

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]

print(sort_array([10, 20, 4, 45,99]))

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

arr = [10, 20, 4, 45, 99]


arr.sort() # [4, 10, 20, 45, 99]
arr.pop() # removes 99 → [4, 10, 20, 45]
return arr[-1] # last element = 45

👉 This works and returns 45, but there are two issues in an interview context:

1. It modifies the original array (in-place sorting + popping).


2. It fails if there are duplicates of the largest value.
Example: [10, 20, 20, 45, 99, 99] → your code would still return 99 instead of 45.

✅ Better & Safer Solution


python

def second_largest(arr):
unique_arr = list(set(arr)) # remove duplicates
unique_arr.sort() # sort
return unique_arr[-2] # second last

print(second_largest([10, 20, 4, 45, 99])) # 45


print(second_largest([10, 20, 20, 45, 99, 99])) # 45

✅ Even More Efficient (without sorting full array)


python

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

print(second_largest([10, 20, 4, 45, 99])) # 45

⚡ 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]

print(sort_array([10, 20, 4, 45,99])) # 5

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]

print(sort_array([10, 20, 4, 45, 99]))

Steps:

arr.sort() → [4, 10, 20, 45, 99]


arr[-2] → 45 ✅
⚠️ But be careful with duplicates:
python

print(sort_array([10, 20, 20, 45, 99, 99]))

Output → 99 ❌ (wrong, should be 45).

✅ Fix using set():

python

def sort_array(arr):
arr = list(set(arr)) # remove duplicates
arr.sort()
return arr[-2]

print(sort_array([10, 20, 4, 45, 99])) # 45


print(sort_array([10, 20, 20, 45, 99, 99])) # 45

💡 In interviews, they often test “what if array has duplicates?”


So, your code is good ✅ but better mention the limitation with duplicates.
👉 Do you want me to now give you the solution for Q3 (check if two strings are anagrams)?

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)

print(anagram("listen", "silent")) # True

Perfect! 🎯
Your solution is clean, correct, and interview-friendly. Let’s break it down so you remember it for
Monday:

✅ Your Code
python

def anagram(s1, s2):


s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
return sorted(s1) == sorted(s2)

print(anagram("listen", "silent")) # True

🔎 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).

✅ Efficient Version (Using Counter)

python

from collections import Counter

def anagram(s1, s2):


s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
return Counter(s1) == Counter(s2)

print(anagram("listen", "silent")) # True


print(anagram("hello", "billion")) # False

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

['r', 'm', 'g']

🔎 If you want counts too:


python

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

{'r': 2, 'g': 2, 'm': 2}

👉 Do you want me to now guide you on Q5 (Find missing number in an array 1 to N)?

CAN you explain the code i dont understand it completely

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

Example with "programming"

1. Start: seen = {}, duplicates = {}


2. First char = 'p' → not in seen → add → seen = {'p'}
3. Next char = 'r' → not in seen → add → seen = {'p','r'}

4. Next char = 'o' → not in seen → add → seen = {'p','r','o'}


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 33/122
5. Next char = 'g' → not in seen → add → seen = {'p','r','o','g'}
6. Next char = 'r' → already in seen → add to duplicates = {'r'}
7. Continue with 'a' → add to seen
8. 'm' → add to seen
9. 'm' again → already in seen → add to duplicates = {'r','m'}

10. 'i' → add to seen


11. 'n' → add to seen
12. 'g' again → already in seen → add to duplicates = {'r','m','g'}

Final: duplicates = {'r','m','g'} → return ['r','m','g']

✅ Version 2: Return duplicates with their counts


python

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:

freq.get(char, 0) → if char not in dict, default to 0


then add 1 each time char appears

Example: "programming"

p:1, r:2, o:1, g:2, a:1, m:2, i:1, n:1

filter only those >1 → {'r':2, 'g':2, 'm':2}

⚡ 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))

🔥 Excellent! You nailed Q5 (Find missing number in an array 1..N).


Let’s go step by step so you’re 100% confident in explaining this during the interview:

✅ Your Code
python

def missing_numbers(n, arr):


expected_sum = (n*(n+1))//2 # sum of numbers from 1 to n
actual_sum = sum(arr) # sum of given numbers
return expected_sum - actual_sum

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).

✅ Version for Multiple Missing Numbers


python

def missing_numbers(n, arr):


full_set = set(range(1, n+1))
return list(full_set - set(arr))

print(missing_numbers(5, [1,3,5])) # [2,4]

👉 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

arr = [x for x in arr if x!=0] # [1,3,12]


arr += [0]*(len(arr) - len(arr)) # len(arr)-len(arr) = 0 → nothing added

✅ Problem: len(arr)changed after removing zeros, so len(arr) - len(arr) = 0.


You need to use original length of the array to calculate how many zeros to append.

✅ 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

print(move_zeros([0,1,0,3,12])) # [1, 3, 12, 0, 0]

Output:

csharp

[1, 3, 12, 0, 0]

🔎 Alternative Efficient Version (In-place, O(n))


python

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]

Why it’s good:

Doesn’t create a new array → works in-place


Faster for large arrays (O(n), no extra memory)

💡 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"))

Good attempt, but there’s a logical issue in your code 😅


❌ Problem
python

a = list(s) # ['h','e','l','l','o',' ','w','o','r','l','d']


b = list(set(a)) # unordered unique letters, e.g. ['h','o','e','w','d','l','r',' ']
return a == b # compares order → will be False even if all unique

set() does not preserve order → comparing a == b won’t work.


Also spaces " " and case should be considered depending on the requirement.

✅ Correct Version (Ignore spaces, case-insensitive)


python

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

Do you want to move to Q8 (First non-repeating character in a string) next?

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

# Count each character


for char in s:
freq[char] = freq.get(char, 0) + 1

# Find first character with count 1


for char in s:
if freq[char] == 1:
return char
return None

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.

3. Returns None if all characters repeat.

Output for "Hello World": 'h' ✅


💡 Interview Tip:
Don’t use sets for this — sets are unordered.
Two-pass solution using a dictionary → O(n) time, O(n) space.

Do you want to try Q9 (Rotate an array by k steps) next?

def rot_array(arr, k):


arr = arr[k:] + arr[:k]
return arr

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

arr = arr[k:] + arr[:k]

This rotates to the left by k positions.


Usually, “rotate by k steps” means rotate to the right (common in interviews).

You wrote k+1 → that will rotate 4 steps instead of 3 (might be a mistake).

✅ Correct Version (Rotate array to the right by k steps)

python

def rotate_array(arr, k):


n = len(arr)
k = k % n # handle k > n
return arr[-k:] + arr[:-k]

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)

🔹 Rotate to the left


If they ask for left rotation, your original logic is correct:

python

arr = arr[k:] + arr[:k]

💡 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

print(longest_common_prefix(["flower", "flow", "flight"]))

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

print(longest_common_prefix(["flower", "flow", "flight"])) # Output: "fl"

🔎 How It Works Step by Step


Input: ["flower", "flow", "flight"]

1. Start: prefix = "flower"


2. Compare with "flow" → "flow".startswith("flower") → False

Remove last char → "flowe" → False


Remove last char → "flow" → True ✅
prefix = "flow"

3. Compare with "flight" → "flight".startswith("flow") → False


Remove last char → "flo" → False
Remove last char → "fl" → True ✅
4. End of loop → return "fl"

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:

Empty list → return ""


No common prefix → return ""

You’ve now solved all 10 array/string problems! 🔥


If you want, we can move to the next batch: Dictionaries, Lambda & OOP — those are very commonly
asked in Xalt Analytics type interviews.
Do you want to continue with dict & lambda problems next?

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.

🔹 Dictionary & Lambda Practice Problems


Q1. Count frequency of elements in a list

python

arr = [1,2,2,3,3,3,4]

# Using dictionary
freq = {}
for x in arr:
freq[x] = freq.get(x,0) + 1

print(freq) # {1:1, 2:2, 3:3, 4:1}

# Using Counter
from collections import Counter
print(Counter(arr)) # Counter({3:3, 2:2, 1:1, 4:1})

Key Tip: dict.get(key,0) is very useful in interviews.

Q2. Sort dictionary by values

python

d = {'a':3, 'b':1, 'c':2}

# 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}

lambda x: x[1] → sorts by value.


x[0] → would sort by key.

Q3. Merge two dictionaries

python

d1 = {'a':1, 'b':2}
d2 = {'b':3, 'c':4}

# Python 3.9+ way


merged = d1 | d2
print(merged) # {'a':1, 'b':3, 'c':4}

# Older way
merged = {**d1, **d2}
print(merged) # {'a':1, 'b':3, 'c':4}

Note: Later dict overrides earlier dict if keys are same.

Q4. Find keys with maximum value in dictionary

python

d = {'a':3, 'b':5, 'c':5, 'd':2}

max_val = max(d.values())
keys = [k for k,v in d.items() if v==max_val]
print(keys) # ['b', 'c']

max(d.values()) → maximum value


List comprehension → find all keys with that value.

Q5. Use lambda for sorting list of tuples

python

arr = [(1, 'b'), (2, 'a'), (3, 'c')]

# Sort by second element


arr.sort(key=lambda x: x[1])
print(arr) # [(2, 'a'), (1, 'b'), (3, 'c')]

Lambda is very powerful for custom sorting in Python.

Q6. Filter dictionary using lambda

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 43/122
python

d = {'a':1, 'b':2, 'c':3, 'd':4}

# Keep only values > 2


filtered = dict(filter(lambda item: item[1]>2, d.items()))
print(filtered) # {'c':3, 'd':4}

filter() with lambda → keeps items satisfying condition.

💡 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.

Do you want to do that next?

ok

Perfect! 🚀 Let’s dive into OOP (Object-Oriented Programming) practice problems.


We’ll cover classes, objects, inheritance, encapsulation, and methods step by step.

🔹 OOP Practice Problems


Q1. Create a simple class and object

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

__salary → private, cannot be accessed directly outside class.

Q3. Inheritance

Problem: Create a Student class that inherits from Person.

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

super().__init__() → calls parent class constructor.

Q4. Class and Static Methods

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

Static method: doesn’t need class instance


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 45/122
Class method: receives class as first argument

Q5. Variable Arguments in OOP

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

*args works inside class methods too.

💡 Interview Tips for OOP:


1. Be ready to explain encapsulation, inheritance, polymorphism, abstraction.

2. Know public, protected (_var), private (__var) variables.


3. Practice creating small classes and objects — they might give a scenario like “Create BankAccount
class with deposit/withdraw”.

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.

🔹 OOP Practice Problems


Q1. Bank Account Class

Problem: Create a BankAccount class with:

Attributes: owner, balance


Methods: deposit(amount), withdraw(amount), display_balance()

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 deposit(self, amount):


self.balance += amount
return f"Deposited {amount}. New balance: {self.balance}"

def withdraw(self, amount):


if amount > self.balance:
return "Insufficient balance"
self.balance -= amount
return f"Withdrew {amount}. New balance: {self.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

Q2. Employee with Protected and Private Variables

python

class Employee:
def __init__(self, name, salary):
self._name = name # protected
self.__salary = salary # private

def get_salary(self):
return self.__salary

def set_salary(self, new_salary):


self.__salary = new_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

Protected _var → convention, can be accessed but not recommended

Private __var → name mangling, cannot access directly

Q3. Inheritance and Method Overriding

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

Q4. Class Method and Static Method

python

class Circle:
pi = 3.14

def __init__(self, radius):


self.radius = radius

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!

Class method → modifies class variable


Static method → utility method, no access to class/instance

Q5. Variable Arguments in Class

python

class Calculator:
def add(self, *args):
return sum(args)

def multiply(self, **kwargs):


result = 1
for key, value in kwargs.items():
result *= value
return result

calc = Calculator()
print(calc.add(1,2,3,4)) # 10
print(calc.multiply(a=2, b=3, c=4)) # 24

*args → tuple of positional arguments


**kwargs → dictionary of keyword arguments

💡 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.

🔹 Pandas Practice Problems


Q1. Create a DataFrame

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

Name Age Department


0 Nishit 21 IT
1 Palak 22 HR
2 Rohan 20 Finance

Q2. Select a column

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

Q3. Filter rows based on condition

python

# Employees with Age > 21


print(df[df['Age'] > 21])

Output:

markdown

Name Age Department


1 Palak 22 HR

Q4. Add a new column

python

df['Salary'] = [50000, 60000, 55000]


print(df)

Output:

markdown

Name Age Department Salary


0 Nishit 21 IT 50000
1 Palak 22 HR 60000
2 Rohan 20 Finance 55000

Q5. Apply a function using apply()

python

# Increase salary by 10%


df['New_Salary'] = df['Salary'].apply(lambda x: x * 1.1)
print(df)

Output:

markdown

Name Age Department Salary New_Salary


0 Nishit 21 IT 50000 55000.0

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

Q6. Grouping and aggregation

python

# Average salary by Department


grouped = df.groupby('Department')['Salary'].mean()
print(grouped)

Output:

yaml

Department
Finance 55000.0
HR 60000.0
IT 50000.0
Name: Salary, dtype: float64

🔹 Interview Tips for Pandas


1. Know DataFrame creation, indexing, filtering, sorting, adding/deleting columns.
2. Practice groupby, apply, lambda, aggregation, merging, handling missing values.
3. Be ready to answer questions like:
“Find top 3 salaries”
“Filter employees with Age < 25 and Salary > 50000”

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.

Do you want to do the mock coding session next?

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.

Problem 1 – Array / List

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]

Constraint: Don’t use division.

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.

Step 1: Understand the problem

For each index i, we want:

python

output[i] = product of all elements except arr[i]

So:

output[0] = 2*3*4 = 24

output[1] = 1*3*4 = 12

etc.

Step 2: Use two passes (prefix and suffix products)

1. Prefix products: Product of all elements before index i


2. Suffix products: Product of all elements after index i

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

i=2: output[2] *= 4 → 2*4 = 8, suffix = 4*3 = 12

i=1: output[1] *= 12 → 1*12 = 12, suffix = 12*2 = 24

i=0: output[0] *= 24 → 1*24 = 24

✅ Final output: [24, 12, 8, 6]

Time complexity: O(n)


Space complexity: O(1) extra space (excluding output array)

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

Great! 🎯 Let’s move to Problem 2 – String Manipulation.


Problem 2 – String

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

# Find first non-repeating character


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"))

Output:

sql

0 # 'l' is the first non-repeating character

🔎 How it works
1. Frequency dictionary:

python

seen = {'l':1, 'e':3, 't':1, 'c':1, 'o':1, 'd':1}

2. Loop through string:


'l' → seen['l'] = 1 → first non-repeating
s.index('l') →0 ✅
⚠️ Minor Improvement
Using s.index(char) inside a loop works, but index() scans the string again → slightly inefficient.

Instead, keep enumeration for O(n) only:

python

def non_repeating_index(s):
s = s.lower().replace(" ", "")
seen = {}

for char in s:
seen[char] = seen.get(char, 0) + 1

for i, char in enumerate(s):


if seen[char] == 1:
return f"{i} # '{char}' is the first non-repeating character"
return -1

print(non_repeating_index("leetcode"))

✅ More efficient because we don’t call .index() repeatedly.

💡 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.

Do you want to move to Problem 3 – Pandas / DataFrame problem next?

ok

Perfect! 🚀 Let’s move to Problem 3 – Pandas / DataFrame problem.


Problem 3 – Pandas

Question:

You have a DataFrame of employee data:

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:

1. Find the average salary for each department.


2. Find the employee(s) with the highest salary in each department.

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.

Step 1: Average salary per department

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)

# Average salary by department


avg_salary = df.groupby('Department')['Salary'].mean()
print("Average Salary per Department:\n", avg_salary)

Output:

yaml

Average Salary per Department:


Department
Finance 65000.0
HR 61000.0
IT 52500.0
Name: Salary, dtype: float64

Step 2: Employee(s) with the highest salary per department

python

# Group by Department and find max salary


max_salary_per_dept = df.groupby('Department')['Salary'].transform('max')

# Filter employees with salary equal to max salary in their department


top_earners = df[df['Salary'] == max_salary_per_dept]
print("\nTop Earners per Department:\n", top_earners)

Output:

css

Top Earners per Department:


Name Department Salary
3 Sneha Finance 65000
4 Amit HR 62000
2 Rohan IT 55000

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.

Do you want to continue with that?

ok

Great! 🚀 Let’s do Problem 4 – Lambda + Dictionary problem.


Problem 4 – Lambda + Dict

Question:
You have a dictionary of students and their scores:

python

students = {'Nishit': 85, 'Palak': 92, 'Rohan': 78, 'Sneha': 92, 'Amit': 70}

Tasks:

1. Find the student(s) with the highest score using lambda.


2. Sort the dictionary by score in descending order using lambda.

Try writing the Python code for this.


If you want, I can solve it step by step for you right now. Do you want me to solve it?

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?

A lambda function is an anonymous (unnamed) function.


Syntax:

python

lambda arguments: expression

It returns the value of the expression automatically.

Example 1 – Add two numbers

python

add = lambda x, y: x + y
print(add(3, 5)) # 8

Equivalent to normal function:

python

def add(x, y):


return x + y

2. Lambda with map()

map() applies a function to every item in a list.

python

nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9, 16]

3. Lambda with filter()

filter() selects items from a list that satisfy a condition.

python

nums = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # [2, 4]

4. Lambda with sorted()

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

students = {'Nishit': 85, 'Palak': 92, 'Rohan': 78}

# Sort by scores descending


sorted_students = dict(sorted(students.items(), key=lambda x: x[1], reverse=True))
print(sorted_students)
# {'Palak': 92, 'Nishit': 85, 'Rohan': 78}

x represents each item (key, value) tuple in the dictionary.


x[1] → the value, i.e., score.

5. Lambda to find max value

python

students = {'Nishit': 85, 'Palak': 92, 'Rohan': 78}

# Max score
max_student = max(students.items(), key=lambda x: x[1])
print(max_student) # ('Palak', 92)

🔹 Key Tips for Interviews


1. Lambda is short, anonymous, and often used with:
map(), filter(), reduce(), sorted(), max(), min()

2. Syntax:

python

lambda arguments: expression

3. Often used to sort dictionaries, filter lists, or calculate inline expressions.

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:

1. Find the student(s) with the highest score.


2. Sort the dictionary by score in descending order.

Step 1: Find student(s) with highest score

python

# Find maximum score


max_score = max(students.values())

# Find all students who have the max score


top_students = list(filter(lambda x: students[x] == max_score, students))
print("Top Students:", top_students)

Output:

css

Top Students: ['Palak', 'Sneha']

Explanation:

students.values() → [85, 92, 78, 92, 70]


max() → 92
filter(lambda x: students[x] == max_score, students) → keeps keys (student names) whose value
equals 92

Step 2: Sort the dictionary by score descending

python

sorted_students = dict(sorted(students.items(), key=lambda x: x[1], reverse=True))


print("Sorted Students by Score:", sorted_students)

Output:

csharp

Sorted Students by Score: {'Palak': 92, 'Sneha': 92, 'Nishit': 85, 'Rohan': 78, 'Amit': 70}

Explanation:

students.items() → [('Nishit',85), ('Palak',92), ...]

key=lambda x: x[1] → sort by value (score)

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

Perfect! 🚀 Let’s do Problem 5 – OOP + Python coding.


Problem 5 – OOP Scenario

Question:
Create a Student class with the following:

1. Attributes: name, roll_no, marks (dictionary of subjects and marks).


2. Methods:
average_marks() → returns the average marks.
top_subject() → returns the subject with the highest marks.

3. Make marks a private attribute.


4. Create two students and display their average and top subject.

Step 1: Implement the Class

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

# Optional: method to access marks

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 62/122
def get_marks(self):
return self.__marks

Step 2: Create Students

python

s1 = Student("Nishit", 101, {"Math": 90, "Physics": 85, "Chemistry": 80})


s2 = Student("Palak", 102, {"Math": 88, "Physics": 92, "Chemistry": 95})

students = [s1, s2]


for s in students:
print(f"{s.name} Average Marks: {s.average_marks()}")
print(f"{s.name} Top Subject: {s.top_subject()}")
print()

Output:

yaml

Nishit Average Marks: 85.0


Nishit Top Subject: Math

Palak Average Marks: 91.66666666666667


Palak Top Subject: Chemistry

🔹 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.

Problem 6 – Rotate Array & Remove Duplicates

Question:
Given an array of integers:

python

arr = [1, 2, 3, 4, 5, 3, 2, 6]

Tasks:

1. Remove duplicates while maintaining order.


2. Rotate the array to the right by k positions (k = 3).

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]

Step 1: Remove duplicates while maintaining order

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)

print("After removing duplicates:", unique_arr)

Output:

less

After removing duplicates: [1, 2, 3, 4, 5, 6]

Step 2: Rotate array to the right by k

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

rotated_arr = unique_arr[-k:] + unique_arr[:-k]


print("After rotation:", rotated_arr)

Output:

less

After rotation: [4, 5, 6, 1, 2, 3]

🔹 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.

3. k = k % n → ensures rotation works even if k > length of array.

✅ 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)

We have now covered all key topics:

Arrays & Strings


Dictionaries & Lambda
OOP & Encapsulation
Pandas / DataFrame operations
Combined Python + DSA

🔥 You are now well-prepared for Xalt Analytics coding rounds!


If you want, I can make a 3-day structured revision plan for your interview so you can practice
efficiently and revise everything before Monday.
Do you want me to do that?

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.

2-Day Rapid Revision Plan

Day 1 – Core Python + DSA + OOP


Morning (3–4 hours) – Python basics & DSA

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:

Write code on paper or IDE without copy-paste


Time yourself for 15–20 min per problem

Afternoon (3 hours) – Dictionaries & Lambda

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:

Emphasize lambda syntax and key points


Keep small examples ready for explanation in interview

Evening (2–3 hours) – OOP

Review concepts: Encapsulation, Inheritance, Polymorphism, Class vs Static methods


Practice 2–3 small problems:

BankAccount, Student class with marks, Employee class

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 66/122
Focus on:
Private & protected variables (_ and __)
Method overriding and super()

Day 2 – Pandas + Mock Coding + Revision


Morning (2–3 hours) – Pandas

DataFrame creation, indexing, filtering, adding columns


groupby, apply, lambda, aggregation
Practice 2–3 problems:

Average salary by department, top earners, filter rows


Review common methods:
df['col'], df.loc, df.iloc, df.groupby(), df.apply()

Afternoon (3–4 hours) – Mock Coding

Solve 4–5 coding problems from all topics:


Array + string + dict + lambda + OOP
Time yourself like real interview: 20–30 min per problem
Focus on:
Writing clean code
Explaining your logic clearly

Evening (2–3 hours) – Revision + Weak Areas

Revise lambda, OOP, and tricky string/array problems


Go through your previously solved mock problems
Practice 1–2 mini full-length mock questions combining all concepts

🔹 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.

🔹 Python & DSA Key Points


Arrays / Lists

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))]

Missing number (1 to n): (n*(n+1))//2 - sum(arr)


Move zeros to end:

python

arr = [x for x in arr if x!=0] + [0]*(arr.count(0))

Strings

Reverse words in string:

python

' '.join(word[::-1] for word in s.split()[::-1])

Check anagram: sorted(s1.replace(" ","").lower()) == sorted(s2.replace(" ","").lower())


First non-repeating char:

python

for i, c in enumerate(s):
if s.count(c) == 1:
return i

Longest common prefix:


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 68/122
python

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

Sort by value descending:

python

sorted_dict = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))

Max value key:

python

max_key = max(d.items(), key=lambda x: x[1])

🔹 Lambda Functions
Syntax: lambda arguments: expression
Examples:

python

# Add two numbers


add = lambda x,y: x+y

# Square numbers
squared = list(map(lambda x: x**2, nums))

# Filter even numbers


even = list(filter(lambda x: x%2==0, nums))

# Sort dict by values descending


sorted_dict = dict(sorted(d.items(), key=lambda x:x[1], reverse=True))

🔹 OOP / Python Classes


Private: __var → cannot access outside class

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__()

Common interview patterns:


BankAccount (deposit/withdraw)

Student class (marks, average, top subject)


Employee class (private salary)

🔹 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')]

🔹 Quick Tips for Interview


1. Explain logic clearly, even if you don’t solve fully.
2. Start with simple approach, optimize if time permits.
3. Mention complexity: time O(n), space O(n).
4. Practice small examples before coding in interview.
5. Review common patterns: arrays, strings, dict + lambda, OOP classes, Pandas groupby.

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

Perfect! 🚀 Let’s start Day 1 Morning – Core Python Basics + DSA.


We’ll focus on arrays/lists, strings, basic DSA patterns, which are high-yield for interviews. I’ll give
short explanations + example problems for practice.

🔹 Core Python Basics + DSA


1️⃣ Arrays / Lists
Reverse an array

python

arr = [1, 2, 3, 4]
rev = arr[::-1] # [4, 3, 2, 1]

Interview tip: arr.reverse() also works but modifies in-place.

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

rot = arr[k:] + arr[:k]

Remove duplicates while maintaining order

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]

Find missing number in 1…n

python

arr = [1,2,4,5]
n = 5
missing = (n*(n+1))//2 - sum(arr)
print(missing) # 3

Move zeros to end

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

s = "I love Python"


rev = ' '.join(word[::-1] for word in s.split()[::-1])
print(rev) # "nohtyP evol I"

Check if two strings are anagrams

python

s1 = "listen"
s2 = "silent"
print(sorted(s1.replace(" ","").lower()) == sorted(s2.replace(" ","").lower())) # True

First non-repeating character

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

Longest common prefix

python

strs = ["flower","flow","flight"]
prefix = strs[0]
for s in strs[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
print(prefix) # "fl"

3️⃣ Quick DSA Patterns


1. Prefix / Suffix products → “product of array except self”
2. Sliding window → sum of subarrays, max/min subarray
3. Hashing → frequency dictionary, duplicates check

✅ Practice Mini Problems


Try solving these 5 problems quickly:

1. Reverse an array without using reverse().


2. Rotate [1,2,3,4,5,6] left by 3 positions.
3. Find missing number in [1,2,4,5,6].

4. Remove duplicates from [1,2,2,3,4,1,5].


5. First non-repeating character in "aabbcdde".

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

Absolutely! 😎 Let’s go problem by problem, giving two versions:


1️⃣ Without pre-built functions – manual logic.
2️⃣ With Python pre-built functions / shortcuts.
We’ll start with the 5 mini problems from before.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 73/122
Problem 1 – Reverse an array
Input: [1, 2, 3, 4]

Version 1 – Without pre-built function

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]

Version 2 – With pre-built function

python

arr = [1, 2, 3, 4]
rev = arr[::-1] # slicing
# OR
arr.reverse() # in-place
rev = arr
print(rev) # [4, 3, 2, 1]

Problem 2 – Rotate array left by k positions


Input: [1,2,3,4,5,6], k=3

Version 1 – Without pre-built function

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]

Version 2 – With pre-built function

python

arr = [1,2,3,4,5,6]
k = 3
rot = arr[k:] + arr[:k]
print(rot) # [4,5,6,1,2,3]

Problem 3 – Find missing number in 1…n


Input: [1,2,4,5,6], n=6

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

Version 2 – With pre-built function

python

arr = [1,2,4,5,6]
n = 6
missing = (n*(n+1))//2 - sum(arr)
print(missing) # 3

Problem 4 – Remove duplicates while maintaining order


Input: [1,2,2,3,4,1,5]

Version 1 – Without pre-built function

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]

Version 2 – With pre-built function

python

arr = [1,2,2,3,4,1,5]
unique = list(dict.fromkeys(arr))
print(unique) # [1,2,3,4,5]

dict.fromkeys(arr) → removes duplicates while maintaining order.

Problem 5 – First non-repeating character


Input: "aabbcdde"
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 75/122
Version 1 – Without pre-built function

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

Version 2 – With pre-built function

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?

more problem related to this

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.

Problem 6 – Count duplicates in an array


Input: [1, 2, 2, 3, 3, 3, 4]
Output: {2:2, 3:3} (number → count)

Version 1 – Without pre-built function

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}

Version 2 – With pre-built function

python

from collections import Counter


arr = [1, 2, 2, 3, 3, 3, 4]
freq = Counter(arr)
duplicates = {k:v for k,v in freq.items() if v>1}
print(duplicates) # {2:2, 3:3}

Problem 7 – Check if array is palindrome


Input: [1,2,3,2,1]
Output: True

Version 1 – Without pre-built function

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

Version 2 – With pre-built function

python

arr = [1,2,3,2,1]
print(arr == arr[::-1]) # True

Problem 8 – Move all negative numbers to start


Input: [1,-2,3,-4,5]
Output: [-2,-4,1,3,5]

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]

Version 2 – With pre-built function

python

arr = [1,-2,3,-4,5]
arr.sort(key=lambda x: x>=0)
print(arr) # [-2,-4,1,3,5]

Problem 9 – Second largest number in array


Input: [10,20,4,45,99]
Output: 45

Version 1 – Without pre-built function

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

Version 2 – With pre-built function

python

arr = [10,20,4,45,99]
arr = list(set(arr))
arr.sort()
print(arr[-2]) # 45

Problem 10 – Count vowels in string

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 78/122
Input: "Hello World"
Output: 3 (e, o, o)

Version 1 – Without pre-built function

python

s = "Hello World"
vowels = "aeiouAEIOU"
count = 0
for c in s:
if c in vowels:
count += 1
print(count) # 3

Version 2 – With pre-built function

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).

🚀 Strings + Dict + Lambda Problems


Problem 11 – Reverse words in a string
Input: "I love Python"
Output: "Python love I"

Version 1 – Without pre-built

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 79/122
python

s = "I love Python"


words = s.split()
rev = []
for i in range(len(words)-1, -1, -1):
rev.append(words[i])
print(" ".join(rev)) # Python love I

Version 2 – With pre-built

python

s = "I love Python"


print(" ".join(s.split()[::-1])) # Python love I

Problem 12 – Check if string is anagram


Input: "listen", "silent" → True

Version 1 – Without pre-built

python

s1, s2 = "listen", "silent"


s1 = s1.replace(" ", "").lower()
s2 = s2.replace(" ", "").lower()
if len(s1) != len(s2):
print(False)
else:
for c in s1:
if s1.count(c) != s2.count(c):
print(False)
break
else:
print(True) # True

Version 2 – With pre-built

python

s1, s2 = "listen", "silent"


print(sorted(s1) == sorted(s2)) # True

Problem 13 – Find frequency of characters


Input: "programming"

Version 1 – Without pre-built

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, ...}

Version 2 – With pre-built

python

from collections import Counter


s = "programming"
print(dict(Counter(s)))

Problem 14 – First unique character


Input: "aabbcdde" → c

Version 1 – Without pre-built

python

s = "aabbcdde"
for i in range(len(s)):
if s.count(s[i]) == 1:
print(s[i]) # c
break

Version 2 – With pre-built

python

from collections import Counter


s = "aabbcdde"
freq = Counter(s)
for c in s:
if freq[c] == 1:
print(c) # c
break

Problem 15 – Remove vowels from string


Input: "Hello World" → "Hll Wrld"

Version 1 – Without pre-built

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

Version 2 – With pre-built

python

s = "Hello World"
print("".join([c for c in s if c.lower() not in "aeiou"]))

Problem 16 – Find longest word in string


Input: "I love programming in Python" → "programming"

Version 1 – Without pre-built

python

s = "I love programming in Python"


words = s.split()
longest = words[0]
for w in words:
if len(w) > len(longest):
longest = w
print(longest) # programming

Version 2 – With pre-built

python

s = "I love programming in Python"


print(max(s.split(), key=len)) # programming

Problem 17 – Sort dictionary by value


Input: {'a':3, 'b':1, 'c':2}

Version 1 – Without pre-built

python

d = {'a':3, 'b':1, 'c':2}


items = list(d.items())
for i in range(len(items)):
for j in range(i+1, len(items)):
if items[i][1] > items[j][1]:
items[i], items[j] = items[j], items[i]
print(dict(items)) # {'b':1, 'c':2, 'a':3}

Version 2 – With pre-built

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 82/122
python

d = {'a':3, 'b':1, 'c':2}


print(dict(sorted(d.items(), key=lambda x: x[1])))

Problem 18 – Square numbers using lambda + map


Input: [1,2,3,4] → [1,4,9,16]

Version 1 – Without pre-built

python

arr = [1,2,3,4]
squares = []
for x in arr:
squares.append(x*x)
print(squares)

Version 2 – With pre-built

python

arr = [1,2,3,4]
print(list(map(lambda x: x*x, arr)))

Problem 19 – Filter even numbers


Input: [1,2,3,4,5,6] → [2,4,6]

Version 1 – Without pre-built

python

arr = [1,2,3,4,5,6]
evens = []
for x in arr:
if x % 2 == 0:
evens.append(x)
print(evens)

Version 2 – With pre-built

python

arr = [1,2,3,4,5,6]
print(list(filter(lambda x: x%2==0, arr)))

Problem 20 – Find word frequency in sentence


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 83/122
Input: "I love Python I love coding"

Version 1 – Without pre-built

python

s = "I love Python I love coding"


words = s.split()
freq = {}
for w in words:
freq[w] = freq.get(w,0) + 1
print(freq) # {'I':2, 'love':2, 'Python':1, 'coding':1}

Version 2 – With pre-built

python

from collections import Counter


s = "I love Python I love coding"
print(dict(Counter(s.split())))

✅ 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

Perfect 🔥 Let’s build your Day 1 Afternoon: DSA Crash Sheet.


We’ll cover core DSA patterns (stacks, queues, linked lists, sorting, searching) in 2 versions each:

Version 1 → Manual logic (no prebuilt functions)


Version 2 → With Python built-ins / libraries

🚀 DSA Crash Problems


Problem 21 – Implement Stack (push, pop, peek)
Version 1 – Manual

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

Version 2 – Using collections.deque

python

from collections import deque

stack = deque()
stack.append(10)
stack.append(20)
print(stack[-1]) # peek -> 20
print(stack.pop()) # pop -> 20

Problem 22 – Implement Queue (enqueue, dequeue)


Version 1 – Manual

python

class Queue:
def __init__(self):
self.items = []

def enqueue(self, item):


self.items.append(item)

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

Version 2 – Using collections.deque

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 85/122
python

from collections import deque

queue = deque()
queue.append(1) # enqueue
queue.append(2)
print(queue.popleft()) # dequeue -> 1

Problem 23 – Reverse a linked list


Version 1 – Manual Node Class

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

Version 2 – Using Python List

python

arr = [1,2,3,4,5]
print(arr[::-1]) # simulate reversed linked list

Problem 24 – Binary Search


Version 1 – Manual

python

def binary_search(arr, target):


left, right = 0, len(arr)-1
while left <= right:
mid = (left+right)//2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid+1
else:
right = mid-1
return -1

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

Problem 25 – Bubble Sort


Version 1 – Manual

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]

Version 2 – Using Python sorted

python

arr = [5,1,4,2,8]
print(sorted(arr)) # [1,2,4,5,8]

Problem 26 – Find Kth largest element


Version 1 – Manual

python

arr = [3,2,1,5,6,4]
k = 2
arr.sort()
print(arr[-k]) # 5

Version 2 – Using heapq

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

Version 2 – Using replace shortcut

python

s = "()[]{}"
while "()" in s or "{}" in s or "[]" in s:
s = s.replace("()", "").replace("{}", "").replace("[]", "")
print(s == "") # True

Problem 28 – Find Peak Element (Binary Search variant)


Version 1 – Manual

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

Version 2 – Using max

python

arr = [1,2,3,1]
print(max(arr)) # 3

✅ With this, you now have:


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 88/122
Day 1 Morning → Core Python (20 problems)
Day 1 Afternoon → DSA Crash Sheet (8 big problems, multiple subpatterns)

Do you want me to now make a Day 2 (SQL + Pandas + Case Studies) crash prep in the same style
(manual + shortcut)?

any more dsa

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

Without prebuilt function

python

def reverse_string(s):
rev = ""
for char in s:
rev = char + rev
return rev

print(reverse_string("hello"))

With prebuilt function

python

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

print(reverse_string("hello"))

2. Check if a String is a Palindrome

Without prebuilt function

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"))

3. Find the Maximum and Minimum in an Array

Without prebuilt function

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]))

With prebuilt function

python

def find_max_min(arr):
return max(arr), min(arr)

print(find_max_min([4, 2, 9, 1, 7]))

4. Find the First Repeated Character

Without prebuilt function

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"))

With prebuilt function

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"))

5. Rotate an Array (k times)

Without prebuilt function

python

def rotate_array(arr, k):


n = len(arr)
k = k % n
result = []
for i in range(k, n):
result.append(arr[i])
for i in range(k):
result.append(arr[i])
return result

print(rotate_array([1,2,3,4,5], 2))

With prebuilt function

python

def rotate_array(arr, k):


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

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

🔹 Day 2 – DSA (Searching, Sorting, Stacks, Queues, Advanced)


11. Binary search (manual & bisect)
12. Bubble sort / Quick sort
13. Merge two sorted arrays
14. Check for anagrams
15. Longest common prefix (strings)
16. Move all zeros to end of array
17. Find intersection of two arrays
18. Check balanced parentheses (stack)
19. Implement queue using list/deque
20. Find majority element (Boyer-Moore)
21. Subarray with given sum

👉 I’ll give you each problem in both ways:


1. Without prebuilt functions (manual logic)
2. With prebuilt functions (using Python features)

This way, you’ll be super ready for your revision.


Do you want me to start writing code & explanations for Day 1 problems first (1–10) right now?

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:

Manual logic (without prebuilt functions)


Pythonic way (with prebuilt functions)

🔹 Problem 1: Reverse a String


python

# (1) Manual logic


def reverse_string(s):
rev = ""
for ch in s:
rev = ch + rev
return rev

print(reverse_string("python")) # nohtyp

# (2) Prebuilt function


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

print(reverse_string_builtin("python")) # nohtyp

🔹 Problem 2: Check Palindrome


python

# (1) Manual logic


def is_palindrome(s):
s = s.lower()
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True

print(is_palindrome("madam")) # True

# (2) Prebuilt
def is_palindrome_builtin(s):
return s.lower() == s[::-1].lower()

print(is_palindrome_builtin("Madam")) # True

🔹 Problem 3: Find Max & Min in Array


python

arr = [10, 2, 56, 7, 34, 89, 1]

# (1) Manual logic

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

print(find_min_max(arr)) # (1, 89)

# (2) Prebuilt
print(min(arr), max(arr)) # (1, 89)

🔹 Problem 4: Find 2nd Largest Element


python

arr = [10, 20, 4, 45, 99]

# (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

🔹 Problem 5: Count Frequency of Characters


python

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

print(char_frequency(s)) # {'p':1, 'r':2, 'o':1, 'g':2, ...}

# (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

# (2) Optimized (prebuilt Counter)


from collections import Counter
def first_non_repeat_builtin(s):
freq = Counter(s)
for ch in s:
if freq[ch] == 1:
return ch
return None

print(first_non_repeat_builtin(s)) # l

🔹 Problem 7: First Repeated Character


python

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

# (2) Prebuilt (Counter)


from collections import Counter
def first_repeated_builtin(s):
freq = Counter(s)
for ch in s:
if freq[ch] > 1:
return ch
return None

print(first_repeated_builtin(s)) # r

🔹 Problem 8: Rotate Array


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 95/122
python

arr = [1,2,3,4,5,6,7]

# (1) Manual left rotate by k


def left_rotate(arr, k):
n = len(arr)
k %= n
return arr[k:] + arr[:k]

print(left_rotate(arr, 2)) # [3,4,5,6,7,1,2]

# (2) Prebuilt (slicing)


def right_rotate(arr, k):
n = len(arr)
k %= n
return arr[-k:] + arr[:-k]

print(right_rotate(arr, 2)) # [6,7,1,2,3,4,5]

🔹 Problem 9: Missing Number in 1..n


python

arr = [1,2,3,5]
n = 5

# (1) Manual (sum formula)


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

print(missing_number(arr, n)) # 4

# (2) Prebuilt (set difference)


def missing_number_builtin(arr, n):
return list(set(range(1, n+1)) - set(arr))[0]

print(missing_number_builtin(arr, n)) # 4

🔹 Problem 10: Remove Duplicates


python

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.

🔹 Extra Day-1 Practice Problems


(Arrays + Strings)

1. Reverse words in a sentence → "I love Python" → "Python love I"


2. Check if two strings are anagrams → "listen" & "silent" → ✅
3. Check if a string is pangram (contains all letters a–z).
4. Find the longest word in a sentence.
5. Find the most frequent element in an array.
6. Check if array is sorted or not.
7. Find common elements between two arrays.
8. Find pair of numbers in array whose sum is target (Two Sum).
9. Find all substrings of a string.
10. Count vowels and consonants in a string.

👉 Each of these can also be solved in two ways:


Manual loop logic
Pythonic prebuilt (set, dict, Counter, etc.)

⚡ 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

Nice💯 Let’s do it step by step.


I’ll give you all 10 extra problems (with manual + prebuilt solutions) so you can revise and practice.

🔹 Extra Day-1 Practice Problems


1. Reverse words in a sentence

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)

print(reverse_words("I love Python")) # Python love I

# (2) Prebuilt
def reverse_words_builtin(sentence):
return " ".join(sentence.split()[::-1])

print(reverse_words_builtin("I love Python")) # Python love I

2. Check if two strings are anagrams

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

print(is_anagram("listen", "silent")) # True

# (2) Prebuilt
def is_anagram_builtin(s1, s2):
return sorted(s1) == sorted(s2)

print(is_anagram_builtin("listen", "silent")) # True

3. Check if a string is pangram

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

print(is_pangram("The quick brown fox jumps over a lazy dog")) # True

# (2) Prebuilt
def is_pangram_builtin(s):
return set(string.ascii_lowercase) <= set(s.lower())

print(is_pangram_builtin("The quick brown fox jumps over a lazy dog")) # True

4. Find the longest word in a sentence

python

sentence = "Python is an amazing programming language"

# (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

5. Find the most frequent element in an array

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

7. Find common elements between two arrays

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

print(common_elements(arr1, arr2)) # [4,5]

# (2) Prebuilt
print(list(set(arr1) & set(arr2))) # [4, 5]

8. Find pair of numbers with given sum (Two Sum)

python

arr = [2, 7, 11, 15]


target = 9

# (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

print(two_sum(arr, target)) # (2, 7)

# (2) Prebuilt (hashing)


def two_sum_builtin(arr, target):
seen = {}
for i, num in enumerate(arr):

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

print(two_sum_builtin(arr, target)) # (2, 7)

9. Find all substrings of a string

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']

# (2) Prebuilt (list comprehension)


print([s[i:j] for i in range(len(s)) for j in range(i+1, len(s)+1)])

10. Count vowels and consonants

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

Sounds perfect 👍 Take a break, recharge ⚡


.
When you’re back, we’ll continue with Day-2 (Searching, Sorting, Stack, Queue, Hashing, etc.) 🚀
Want me to remind you with a quick warm-up quiz when you return, or straight into new topics?

ok lets continue todays revision

Awesome 🚀 Welcome back!


We finished Day-1 (Core Python + Arrays + Strings). Now let’s continue with Day-2 (Advanced DSA +
Interview-style problems).
Here’s the plan for today’s revision:

🔹 Day-2 Problems (Advanced DSA in Python)


11. Binary Search (manual + bisect module)
12. Sorting (Bubble Sort, Quick Sort, Built-in sort)
13. Merge two sorted arrays
14. Check Anagram (optimized)
15. Longest Common Prefix (strings)
16. Move all zeros to end
17. Find intersection of two arrays
18. Check Balanced Parentheses (stack)
19. Implement Queue (list & deque)
20. Majority Element (Boyer-Moore Voting Algo)
21. Subarray with given sum

👉 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

Perfect 👍 Let’s start with Problem 11: Binary Search.


This is a very common interview problem.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 102/122
🔹 Problem 11: Binary Search
Definition

Binary search is an efficient algorithm to find an element in a sorted array.

Time Complexity: O(log n)


Space Complexity: O(1)

✅ (1) Manual Implementation


python

def binary_search(arr, target):


left, right = 0, len(arr) - 1

while left <= right:


mid = (left + right) // 2

if arr[mid] == target:
return mid # return index
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1

return -1 # not found

arr = [2, 4, 7, 10, 14, 18, 21]


print(binary_search(arr, 10)) # 3
print(binary_search(arr, 5)) # -1

✅ (2) Using Python Built-in ( bisect)

python

import bisect

arr = [2, 4, 7, 10, 14, 18, 21]

# Find position where 10 should be inserted


pos = bisect.bisect_left(arr, 10)

if pos < len(arr) and arr[pos] == 10:


print("Found at index:", pos) # Found at index: 3
else:
print("Not found")

👉 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

Great 👍 Let’s continue with Problem 12: Sorting.


Sorting is another favorite in interviews — they sometimes ask you to implement it manually and also
know Python’s built-in ways.

🔹 Problem 12: Sorting


Definition

Sorting means arranging elements in ascending or descending order.

Common algorithms: Bubble Sort, Quick Sort, Merge Sort.

Python has Timsort (used in sort() and sorted()), which is highly optimized.

✅ (1) Bubble Sort (Manual Implementation)


python

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

arr = [64, 25, 12, 22, 11]


print(bubble_sort(arr)) # [11, 12, 22, 25, 64]

Time Complexity: O(n²)


Space Complexity: O(1)

✅ (2) Quick Sort (Recursive Implementation)


python

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)

arr = [64, 25, 12, 22, 11]


print(quick_sort(arr)) # [11, 12, 22, 25, 64]

Average Time Complexity: O(n log n)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 104/122
Worst Case: O(n²) (if bad pivot chosen)

✅ (3) Python Built-in Sorting


python

arr = [64, 25, 12, 22, 11]

print(sorted(arr)) # [11, 12, 22, 25, 64]


arr.sort()
print(arr) # [11, 12, 22, 25, 64]

# Descending
print(sorted(arr, reverse=True)) # [64, 25, 22, 12, 11]

👉 In interviews, they may ask you:


Implement Bubble Sort or Quick Sort manually.
Explain why Python uses Timsort.
Sort by custom key (like sorting by string length, or dictionary values).

⚡ 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?

yes by custom cunditio

Perfect👍 Let’s cover Sorting by Custom Condition because interviewers often test this with
dictionaries, tuples, or objects.

🔹 Problem 13: Sorting by Custom Condition


✅ (1) Sort strings by length
python

words = ["apple", "banana", "kiwi", "cherry", "mango"]

# Sort by length (ascending)


print(sorted(words, key=len))
# ['kiwi', 'mango', 'apple', 'banana', 'cherry']

# Sort by length (descending)


print(sorted(words, key=len, reverse=True))
# ['banana', 'cherry', 'apple', 'mango', 'kiwi']

✅ (2) Sort dictionary by values


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 105/122
python

scores = {"Alice": 85, "Bob": 72, "Charlie": 90, "David": 65}

# Sort by values (ascending)


print(sorted(scores.items(), key=lambda x: x[1]))
# [('David', 65), ('Bob', 72), ('Alice', 85), ('Charlie', 90)]

# Sort by values (descending)


print(sorted(scores.items(), key=lambda x: x[1], reverse=True))
# [('Charlie', 90), ('Alice', 85), ('Bob', 72), ('David', 65)]

✅ (3) Sort list of tuples by second element


python

students = [("Alice", 22), ("Bob", 19), ("Charlie", 25)]

# Sort by age (2nd element)


print(sorted(students, key=lambda x: x[1]))
# [('Bob', 19), ('Alice', 22), ('Charlie', 25)]

✅ (4) Sort objects by an attribute


python

class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks

def __repr__(self):
return f"{self.name}({self.marks})"

students = [Student("Alice", 85), Student("Bob", 72), Student("Charlie", 90)]

# 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

Great 🚀 Let’s practice Custom Sorting Problems before we move on.


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 106/122
🔹 Custom Sorting Practice
Q1. Sort strings by length, then alphabetically

Input:

python

words = ["pear", "apple", "banana", "kiwi", "cherry"]

Expected Output:

css

['kiwi', 'pear', 'apple', 'banana', 'cherry']

👉 First by length, if same length → sort alphabetically.


Q2. Sort employees by salary, then by name

Input:

python

employees = [("Alice", 50000), ("Bob", 40000), ("Charlie", 50000), ("David", 60000)]

Expected Output:

css

[("Bob", 40000), ("Alice", 50000), ("Charlie", 50000), ("David", 60000)]

👉 If two employees have the same salary → sort by name.


Q3. Sort tuples by 2nd element (descending), then 1st element (ascending)

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)]

Q4. Sort dictionary by values (descending), then keys (ascending)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 107/122
Input:

python

scores = {"Alice": 85, "Bob": 72, "Charlie": 85, "David": 90}

Expected Output:

css

[('David', 90), ('Alice', 85), ('Charlie', 85), ('Bob', 72)]

Q5. Sort students (objects) by marks, then name

python

class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks

def __repr__(self):
return f"{self.name}({self.marks})"

students = [Student("Alice", 85), Student("Bob", 72), Student("Charlie", 85), Student("David",


90)]

Expected Output:

csharp

[Bob(72), Alice(85), Charlie(85), David(90)]

👉 If marks are equal, sort by name.


⚡ You can solve these in two versions:
1. Without prebuilt functions (manual sorting logic like bubble sort).
2. With sorted() + lambda.

Do you want me to solve one as an example (both ways), and you try the rest?

give me the ans of these

Perfect 👍 Let’s solve all 5 custom sorting problems in two versions:


✅ Q1. Sort strings by length, then alphabetically
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 108/122
🔹 Without prebuilt sorted()

python

words = ["pear", "apple", "banana", "kiwi", "cherry"]

# Bubble Sort with custom condition


for i in range(len(words)):
for j in range(len(words)-1):
if len(words[j]) > len(words[j+1]) or (len(words[j]) == len(words[j+1]) and words[j] >
words[j+1]):
words[j], words[j+1] = words[j+1], words[j]

print(words)

🔹 With sorted() + lambda

python

words = ["pear", "apple", "banana", "kiwi", "cherry"]


print(sorted(words, key=lambda x: (len(x), x)))

✅ Q2. Sort employees by salary, then by name


🔹 Without prebuilt
python

employees = [("Alice", 50000), ("Bob", 40000), ("Charlie", 50000), ("David", 60000)]

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

employees = [("Alice", 50000), ("Bob", 40000), ("Charlie", 50000), ("David", 60000)]


print(sorted(employees, key=lambda x: (x[1], x[0])))

✅ 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])))

✅ Q4. Sort dictionary by values (desc), then keys (asc)


🔹 Without prebuilt
python

scores = {"Alice": 85, "Bob": 72, "Charlie": 85, "David": 90}


items = list(scores.items())

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

scores = {"Alice": 85, "Bob": 72, "Charlie": 85, "David": 90}


print(sorted(scores.items(), key=lambda x: (-x[1], x[0])))

✅ Q5. Sort students (objects) by marks, then name


🔹 Without prebuilt
python

class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks

def __repr__(self):
return f"{self.name}({self.marks})"

students = [Student("Alice", 85), Student("Bob", 72), Student("Charlie", 85), Student("David",


90)]

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})"

students = [Student("Alice", 85), Student("Bob", 72), Student("Charlie", 85), Student("David",


90)]

print(sorted(students, key=lambda s: (s.marks, s.name)))

🔥 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?

ok next dsa question

Great 🚀 Let’s move to the next DSA question.


We already did sorting variations. Now let’s do a classic merging problem 👇
✅ Problem: Merge Two Sorted Arrays
👉 Given two sorted arrays, merge them into one sorted array.
🔹 Approach 1: Without built-in sort (Two Pointers)
python

def merge_sorted_arrays(arr1, arr2):


i, j = 0, 0
merged = []

while i < len(arr1) and j < len(arr2):


if arr1[i] < arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1

# Add remaining elements

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 111/122
while i < len(arr1):
merged.append(arr1[i])
i += 1

while j < len(arr2):


merged.append(arr2[j])
j += 1

return merged

print(merge_sorted_arrays([1, 3, 5], [2, 4, 6]))

✅ Output:
csharp

[1, 2, 3, 4, 5, 6]

🔹 Approach 2: With built-in function


python

def merge_sorted_arrays_builtin(arr1, arr2):


return sorted(arr1 + arr2)

print(merge_sorted_arrays_builtin([1, 3, 5], [2, 4, 6]))

✅ Output:
csharp

[1, 2, 3, 4, 5, 6]

⚡ This is the basis of Merge Sort.


Do you want me to go one step deeper and explain how merge sort uses this idea?

ok next

Nice ⚡ Moving on to the next important DSA question:


✅ Problem: Check Balanced Parentheses
👉 Given a string containing ()[]{},
check if it is balanced.
Balanced means every opening bracket has a correct closing bracket in the right order.

🔹 Approach 1: Without built-in stack (using list as stack)


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 112/122
python

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

🔹 Approach 2: Using Python’s collections.deque

python

from collections import deque

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

⚡ This problem is very common in coding interviews because it tests:


Stack knowledge
Condition handling
Edge cases

👉 Do you want me to now give you a slight twist version of this (like checking HTML/XML tag
balancing)?

ok next

Perfect ✅ Let’s move to the next classic DSA problem:


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 113/122
✅ Problem: Implement Queue
We’ll cover two versions:

1. Using a list
2. Using Python’s collections.deque

🔹 Approach 1: Queue using list


python

class QueueList:
def __init__(self):
self.queue = []

def enqueue(self, val):


self.queue.append(val)

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

⚠️ Note: pop(0) in list is O(n), so not efficient for large queues.

🔹 Approach 2: Queue using deque

python

from collections import deque

class QueueDeque:
def __init__(self):
self.queue = deque()

def enqueue(self, val):


self.queue.append(val)

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

Perfect ✅ Let’s move to Stack Implementation, another classic DSA topic.


✅ Problem: Implement Stack
We’ll cover two versions:

1. Using a list
2. Using Python’s collections.deque

🔹 Approach 1: Stack using list


python

class StackList:
def __init__(self):
self.stack = []

def push(self, val):


self.stack.append(val)

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

🔹 Approach 2: Stack using deque

python

from collections import deque

class StackDeque:
def __init__(self):
self.stack = deque()

def push(self, val):


self.stack.append(val)

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.

Example: [3, 3, 4, 2, 3, 3, 3] → Majority element is 3.

🔹 Approach 1: Using Hash Map (Manual Counting)


python

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

Time Complexity: O(n)


Space Complexity: O(n)

🔹 Approach 2: Boyer-Moore Voting Algorithm (Optimal)


python

def majority_element_boyer_moore(arr):
candidate = None
count = 0

for num in arr:


if count == 0:
candidate = num
count = 1
elif num == candidate:
count += 1
else:
count -= 1

# Optional: verify candidate is actually majority


if arr.count(candidate) > len(arr)//2:
return candidate
return None

arr = [3, 3, 4, 2, 3, 3, 3]
print(majority_element_boyer_moore(arr)) # 3

Time Complexity: O(n)


Space Complexity: O(1) ✅
🔑 Interview Tip:
Hash map is simple but uses extra space.

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]

🔹 Approach 1: Brute Force (Manual)


python

def subarray_sum_brute(arr, target):


n = len(arr)
for start in range(n):
curr_sum = 0
for end in range(start, n):
curr_sum += arr[end]
if curr_sum == target:
return arr[start:end+1] # return subarray
return None

arr = [1, 2, 3, 7, 5]
target = 12
print(subarray_sum_brute(arr, target)) # [2, 3, 7]

Time Complexity: O(n²)


Space Complexity: O(1)

🔹 Approach 2: Using Hash Map (Optimized, Prefix Sum)


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 118/122
python

def subarray_sum_hash(arr, target):


prefix_sum = 0
seen = {0: -1} # prefix sum → index

for i, num in enumerate(arr):


prefix_sum += num
if (prefix_sum - target) in seen:
start = seen[prefix_sum - target] + 1
return arr[start:i+1]
seen[prefix_sum] = i
return None

arr = [1, 2, 3, 7, 5]
target = 12
print(subarray_sum_hash(arr, target)) # [2, 3, 7]

Time Complexity: O(n)


Space Complexity: O(n)

🔑 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.

After this, we will have covered Day-2 essential DSA:

Binary Search
Sorting & Custom Sorting
Merge Two Sorted Arrays

Stack & Queue


Balanced Parentheses
Majority Element
Subarray Sum

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

Perfect! Let’s break it down clearly before we summarize.

🔹 1️⃣ Hash Map in Python


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 119/122
A hash map (also called dictionary) is a data structure that maps keys to values.

Time complexity:
Lookup: O(1) average
Insert: O(1) average

Example

python

# Create a hash map


student_scores = {"Alice": 85, "Bob": 72, "Charlie": 90}

# Access value by key


print(student_scores["Alice"]) # 85

# Add/update value
student_scores["David"] = 65
student_scores["Alice"] = 95

# Check if key exists


if "Bob" in student_scores:
print("Bob is in the hash map")

# Iterate over keys and values


for key, value in student_scores.items():
print(key, value)

Usage in DSA:

Count frequencies of elements


Store prefix sums
Check existence of complements (Two Sum problem)
Track first occurrence of elements

🔹 2️⃣ Sliding Window Technique


A sliding window is a technique to solve array/string problems efficiently when we need subarrays or
substrings.

Idea: Keep a window (start, end) and move it forward instead of recomputing sums or counts
from scratch.
Time complexity: O(n)

Example: Max Sum of Subarray of Size k

python

arr = [1, 2, 3, 4, 5]
k = 3

# Sliding window sum

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:

Maximum/minimum subarray sum


Longest substring with unique characters
Subarray with given sum (if all elements positive)

🔹 Summary of Day-1 + Day-2 Problems


# Problem Key Concept Manual / Built-in
1 Reverse words Strings, slicing manual + split[::-1]
2 Anagram Strings, count/sort manual + sorted()
3 Pangram Strings, sets manual + set()
4 Longest word Strings manual + max(key=len)
5 Most frequent element Counting, dict manual + Counter()
6 Check array sorted Arrays manual + sorted()
7 Intersection of arrays Sets manual + set()
8 Two Sum Hash map manual + dict / hashmap
9 All substrings Strings manual + list comprehension
10 Count vowels/consonants Strings manual + regex
11 Binary Search Arrays, divide & conquer manual + bisect

12 Sorting Arrays manual + sorted()


13 Merge two sorted arrays Arrays, two pointers manual + sorted()
14 Check balanced parentheses Stack manual + deque
15 Stack Stack manual list + deque
16 Queue Queue manual list + deque
17 Majority Element Hash map / Boyer-Moore manual + O(1) optimal
18 Subarray with given sum Hash map / sliding window manual + prefix sum
19 Custom sorting Sorted by conditions manual + sorted(lambda)

💡 Key Takeaways for Interviews:


1. Manual + Built-in: Always know both.
2. Hash maps are crucial for frequency counting and prefix sums.
3. Sliding window helps solve subarray / substring problems in O(n).
4. Stack & Queue: Know list vs deque efficiency.

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

You might also like