
In this chapter, we will discuss the significance of Data Structures and Algorithms (DSA) in computer science and the tech industry. Understanding why DSA is essential will motivate and guide your learning throughout this course.
In this chapter, we'll dive into the basic data types in Python—integers, floats, and strings. You'll learn how to write and manipulate these data types with actual Python code.
Integers (int):
Whole numbers, positive or negative, without decimals.
#code
x = 10
y = -5
print(x + y) # Output: 5
Floats (float):
Numbers with decimal points.
#code
a = 5.5
b = 2.3
print(a * b) # Output: 12.65
Booleans (bool):
Represents True or False.
#code
is_valid = True
print(is_valid) # Output: True
Strings (str):
Sequence of characters.
#code
greeting = "Hello"
name = "Alice"
print(greeting + " " + name) # Output: Hello Alice
Reads a string from user input.
#code
# Here + is used for adding strings, we will learn in future videos.
user_input = input("Enter your name: ")
print("Hello, " + user_input)
Converting one data type to another.
Integer to Float:
#code
x = 5
y = float(x)
print(y) # Output: 5.0
Float to Integer:
#Code
a = 3.8
b = int(a)
print(b) # Output: 3
String to Integer:
#Code
s = "123"
num = int(s)
print(num) # Output: 123
String to Float:
#Code
s = "45.67"
num = float(s)
print(num) # Output: 45.67
Boolean to Integer:
#Code
is_valid = True
num = int(is_valid)
print(num) # Output: 1
In this chapter, we will explore the concepts of lists and arrays in Python. We'll start by understanding what arrays are and how they differ from lists. Then, we'll delve into common list operations such as append() and insert(), and learn about indexing.
#code
# Array
import array
arr = array.array('i', [1, 2, 3, 4, 5])
print(arr) # Output: array('i', [1, 2, 3, 4, 5])
- Difference Between Array and List:
Arrays: Homogeneous data types, require importing the array module.
Lists: Can store heterogeneous data types, built-in to Python.
#code
# List
my_list = [1, "Hello", 3.4]
# Array
import array
my_array = array.array('i', [1, 2, 3])
- List Operations - append()
Adds an element to the end of the list.
#code
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
- List Operations - insert()
Inserts an element at a specified position.
#code
my_list = [1, 2, 3]
my_list.insert(1, 'a')
print(my_list) # Output: [1, 'a', 2, 3]
- Understanding Indexing
Accessing elements by their index.
#code
my_list = ['a', 'b', 'c', 'd']
print(my_list[1]) # Output: 'b'
print(my_list[-1]) # Output: 'd'
In this chapter, we will expand our understanding of lists by exploring advanced operations such as slicing, pop(), remove(), extend(), appending one list to another, and combining lists using the + operator. Additionally, we'll introduce the concept of tuples in Python.
- List Slicing
Extracting a portion of a list using slicing.
#code
my_list = [1, 2, 3, 4, 5]
slice1 = my_list[1:3] # Output: [2, 3]
slice2 = my_list[:2] # Output: [1, 2]
slice3 = my_list[3:] # Output: [4, 5]
slice4 = my_list[::2] # Output: [1, 3, 5]
- pop():
Removes and returns an element from a specified position (default is the last item).
#code
my_list = [1, 2, 3, 4]
popped_item = my_list.pop(2)
print(popped_item) # Output: 3
print(my_list) # Output: [1, 2, 4]
- remove():
Removes the first occurrence of a specified value.
#coding
my_list = [1, 2, 3, 4, 3]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 3]
- extend():
Extends the list by appending elements from another list.
#coding
list1 = [1, 2, 3]
list2 = [4, 5]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5]
- Appending a List to Another List:
Adding a list as a single element to another list.
#code
list1 = [1, 2, 3]
list2 = [4, 5]
list1.append(list2)
print(list1) # Output: [1, 2, 3, [4, 5]]
Combining Lists with +:
Combining two lists into a new list.
#code
list1 = [1, 2, 3]
list2 = [4, 5]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5]
Introduction to Tuples:
Immutable(can't change) sequences of elements.
#coding
my_tuple = (1, 2, 3)
print(my_tuple) # Output: (1, 2, 3)
print(my_tuple[1]) # Output: 2
In this chapter, we will explore the fundamentals of strings in Python. We will cover string concatenation, which is the process of joining two or more strings together, and string slicing, which allows you to extract specific parts of a string.
Strings are sequences of characters enclosed in quotes.
#coding
my_string = "Hello, World!"
print(my_string) # Output: Hello, World!
Joining two or more strings together using the + operator.
#coding
str1 = "Hello"
str2 = "World"
concatenated_str = str1 + " " + str2
print(concatenated_str) # Output: Hello World
Extracting a portion of a string using slicing.
#coding
my_string = "Hello, World!"
slice1 = my_string[0:5] # Output: Hello
slice2 = my_string[7:12] # Output: World
slice3 = my_string[::2] # Output: Hlo ol!
slice4 = my_string[::-1] # Output: !dlroW ,olleH
In this chapter, we will explore dictionaries in Python, a versatile data structure that allows you to store key-value pairs. We will cover essential operations such as updating keys and values, adding new key-value pairs, deleting items, and using various dictionary methods like keys(), values(), and items(). Additionally, we will learn how to check for the presence of keys using the in operator.
Dictionaries store data as key-value pairs.
#coding
my_dict = {"name": "Alice", "age": 25}
print(my_dict) # Output: {'name': 'Alice', 'age': 25}
Modifying an existing key-value pair.
#coding
my_dict["age"] = 26
print(my_dict) # Output: {'name': 'Alice', 'age': 26}
Adding a new key-value pair to the dictionary.
#coding
my_dict["city"] = "New York"
print(my_dict) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Removing a key-value pair from the dictionary.
#coding
del my_dict["age"]
print(my_dict) # Output: {'name': 'Alice', 'city': 'New York'}
Checking if a key exists in the dictionary.
#coding
if "name" in my_dict:
print("Name is present") # Output: Name is present
keys(): Returns a view object of all keys.
#coding
keys = my_dict.keys()
print(keys) # Output: dict_keys(['name', 'city'])
values(): Returns a view object of all values.
#coding
keys = my_dict.keys()
print(keys) # Output: dict_keys(['name', 'city'])
items(): Returns a view object of all key-value pairs
In this chapter, we will dive into sets in Python, a powerful data structure that stores unordered and unique elements. We will learn how to initialize an empty set, create a set with initial elements, and use the type() function to identify the data type. We'll explore the key differences between lists and sets, focusing on the unordered nature and uniqueness of elements in sets. Additionally, we will cover how to add and remove elements from a set, handle duplicate elements, and convert sets to lists. Finally, we'll see how to convert a list with repeated elements into a list of unique elements using sets.
Sets are collections of unordered and unique elements.
#code
my_set = {1, 2, 3}
print(my_set) # Output: {1, 2, 3}
Initializing an Empty Set:
- Using the set() function to create an empty set.
#code
empty_set = set()
print(empty_set) # Output: set()
Creating a Set with Initial Elements:
- Defining a set with some elements at the start.
#code
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
Using type():
- Checking the type of a set.
#code
my_set = {1, 2, 3}
print(type(my_set)) # Output: <class 'set'>
Difference Between List and Set:
- Lists are ordered and can contain duplicate elements.
- Sets are unordered and contain unique elements.
#code
my_list = [1, 2, 2, 3]
my_set = {1, 2, 2, 3}
print(my_list) # Output: [1, 2, 2, 3]
print(my_set) # Output: {1, 2, 3}
No Order and Unique Elements:
Sets do not maintain order and automatically remove duplicates.
#code
my_set = {3, 1, 2, 3}
print(my_set) # Output: {1, 2, 3}
Adding New Elements:
Using the add() method to add elements to a set.
#code
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
Removing Elements:
- Using the remove() method to remove elements from a set.
#code
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
Handling Multiple Elements:
- Adding duplicate elements does not change the set.
#code
my_set = {1, 2, 3}
my_set.add(3)
print(my_set) # Output: {1, 2, 3}
Converting Set to List:
- Using the list() function to convert a set to a list.
#code
my_set = {1, 2, 3}
my_list = list(my_set)
print(my_list) # Output: [1, 2, 3]
Converting List with Repeated Elements to Unique Elements:
- Using a set to remove duplicates from a list and then converting back to a list.
#code
my_list = [1, 2, 2, 3, 3, 3]
my_unique_list = list(set(my_list))
print(my_unique_list) # Output: [1, 2, 3]
In this chapter, we will learn how to perform a linear search using the in operator in Python. We will also use the map() function to take user input of space-separated values, converting them into a list for searching. This will give you a practical introduction to user input handling and basic search techniques in Python.
Linear Search Using in Operator:
- Understanding how the in operator can be used for linear search.
#code
my_list = [10, 20, 30, 40, 50]
target = 30
if target in my_list:
print(f"{target} found in the list")
else:
print(f"{target} not found in the list")
Using map() to Take User Input:
- Taking space-separated user input and converting it into a list of integers.
#code
# Taking space-separated input from the user and converting to a list of integers
user_input = input("Enter space-separated numbers: ")
my_list = list(map(int, user_input.split()))
print("The list is:", my_list)
Taking User Input:
- Use the input() function to capture space-separated numbers from the user.
- Use split() to split the input string into individual components.
- Use map() to apply the int function to each component, converting them into integers.
Convert the map object to a list.
#code
# Example of taking user input and converting to list
user_input = input("Enter space-separated numbers: ")
my_list = list(map(int, user_input.split()))
print("The list is:", my_list)
Performing Linear Search Using in:
- Use the in operator to check if the target element exists in the list.
- Print an appropriate message based on the result.
#code
# Example of performing linear search using 'in'
target = int(input("Enter the number to search for: "))
if target in my_list:
print(f"{target} found in the list")
else:
print(f"{target} not found in the list")
Combining User Input and Linear Search:
- Combine the above steps to create a complete program that takes user input, converts it to a list, and performs a linear search.
#code
# Complete program
user_input = input("Enter space-separated numbers: ")
my_list = list(map(int, user_input.split()))
print("The list is:", my_list)
target = int(input("Enter the number to search for: "))
if target in my_list:
print(f"{target} found in the list")
else:
print(f"{target} not found in the list")
In this chapter, we will explore how linear searching works behind the scenes. You will learn how to check elements one by one and verify if the element at any index is equal to the target. We will also cover the usage of if, elif, and else statements in Python to control the flow of the search logic.
Assume a list with a fixed number of elements and a target value.
- Use if, elif, and else statements to manually check each element.
#code
my_list = [10, 20, 30, 40, 50]
target = 30
if my_list[0] == target:
print(f"{target} found at index 0")
elif my_list[1] == target:
print(f"{target} found at index 1")
elif my_list[2] == target:
print(f"{target} found at index 2")
elif my_list[3] == target:
print(f"{target} found at index 3")
elif my_list[4] == target:
print(f"{target} found at index 4")
else:
print(f"{target} not found in the list")
In this chapter, we will perform a linear search using a while loop. This approach will help you understand how to control the flow of a program using loops and conditional statements, ensuring you can efficiently search through a list to find a target element.
Linear Search Using while Loop:
- Using a while loop to iterate through a list.
- Using a flag variable (isPresent) to indicate if the target is found.
Flag Variable:
- Understanding the use of a flag variable to manage search results.
#code
isPresent = False
Step-by-Step Guide:
1. Initialize Variables:
- Create a list and a target value.
- Initialize an index variable to start the loop.
- Initialize the flag variable (isPresent) to False
#code
my_list = [10, 20, 30, 40, 50]
target = 30
index = 0
isPresent = False
2. Perform Linear Search Using while Loop:
- Use a while loop to iterate through the list.
- Check each element with the target.
- If the element is found, set isPresent to True and break the loop.
- Increment the index in each iteration.
#code
while index < len(my_list):
if my_list[index] == target:
isPresent = True
break
index += 1
3. Check the Flag Variable:
- Use an if statement to check the value of isPresent.
- Print an appropriate message based on whether the target was found or not.
#code
if isPresent:
print(f"{target} found at index {index}")
else:
print(f"{target} not found in the list")
#code
# Initialize variables
my_list = [10, 20, 30, 40, 50]
target = 30
index = 0
isPresent = False
# Perform linear search using while loop
while index < len(my_list):
if my_list[index] == target:
isPresent = True
break
index += 1
# Check the flag variable and print the result
if isPresent:
print(f"{target} found at index {index}")
else:
print(f"{target} not found in the list")
In this chapter, we will perform a linear search using a for loop. You will learn how to use the range function and for loop to iterate through a list and find a target element. This approach will help you understand how loops work in Python and how they can be used to efficiently search through a list.
The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range).
#code
lst = [2,4,5,7,12,10]
for item in lst:
print(item)
The range function generates a sequence of numbers.
#code
for i in range(5): # generates numbers 0 to 4
print(i)
# Initialize variables
#code
my_list = [10, 20, 30, 40, 50]
target = 30
isPresent = False
# Perform linear search using for loop
for i in range(len(my_list)):
if my_list[i] == target:
isPresent = True
index = i
break
# Check the flag variable and print the result
if isPresent:
print(f"{target} found at index {index}")
else:
print(f"{target} not found in the list")
In this chapter, we will cover the fundamentals of defining and calling functions in Python. Understanding the difference between function definition and function calling is crucial for structuring your code effectively. Additionally, we will explore how to use the end parameter in the print function and how to write reusable functions.
Defining Functions:
- A function definition specifies the name of the function and the sequence of statements that make up the function.
#code
def greet(name):
print(f"Hello, {name}!")
Calling Functions:
- To execute the function's code, you need to call the function by its name followed by parentheses.
- If the function requires parameters, you provide the arguments within the parentheses.
#code
greet("Alice") # Output: Hello, Alice!
Definition vs Calling:
- Definition: Creating the function and specifying its behavior.
- Calling: Executing the function's behavior using its name.
#code
# Function definition
def add(a, b):
print(a+b)
# Function calling
add(3, 4) # Output: 7
Using end in print:
- The end parameter in the print function specifies what to print at the end of the given text. The default is a newline character (\n), but it can be changed to any string.
#code
print("Hello", end=" ")
print("World")
# Output: Hello World
Writing Reusable Functions:
- Reusable functions are designed to perform a specific task and can be used multiple times in different parts of the code.
- Keep functions focused on a single task.
- Use parameters to make functions flexible.
#code
def multiply(a, b):
print(a * b)
multiply(2, 3) # Output: 6
multiply(4, 5) # Output: 20
In this chapter, we will explore how to pass and receive different types of arguments in functions. We will cover positional arguments, keyword arguments, default arguments, and variable-length arguments. Additionally, we will discuss what happens when a function does not return anything.
Passing and Receiving Arguments:
- Functions can take any number of arguments and process them to
produce a result.
- Positional arguments are the most common way to pass values to a function.
#code
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Output: 7
Keyword Arguments:
- Keyword arguments allow you to specify the value of a parameter by name, providing more clarity and flexibility.
#code
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet(name="Alice", greeting="Hi") # Output: Hi, Alice!
greet("Bob") # Output: Hello, Bob!
Default Arguments:
- Default arguments provide default values for parameters, making them optional when calling the function.
#code
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Charlie") # Output: Hello, Charlie!
greet("Dana", "Hi") # Output: Hi, Dana!
Variable-Length Arguments:
- Variable-length arguments allow a function to accept an arbitrary number of arguments.
- Use *args for non-keyword variable-length arguments and **kwargs for keyword variable-length arguments.
#code
# Using *args for variable-length arguments
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4)) # Output: 10
# Using **kwargs for keyword variable-length arguments
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Eve", age=30, city="New York")
# Output:
# name: Eve
# age: 30
# city: New York
Functions without Return Values:
- A function that does not explicitly return a value will return None by default.
#cod
def greet(name):
print(f"Hello, {name}!")
result = greet("Frank")
print(result) # Output: Hello, Frank! followed by None
In this chapter, we will explore the concepts of mutable and immutable types in Python. We will discuss why certain types like int, str, and bool are immutable, while types like list, set, and dictionary are mutable. Additionally, we will learn how to modify mutable types inside a function and the implications of passing mutable objects to functions.
Mutable vs Immutable Types:
- Immutable Types: Objects whose state cannot be changed after they are created. Examples include int, str, bool, and float.
- Mutable Types: Objects whose state can be changed after they are created. Examples include list, set, and dict.
Why Certain Types are Immutable:
- Efficiency and Safety: Immutable types are more memory-efficient and can be used as keys in dictionaries and elements in sets due to their hashable nature.
- Consistency: Immutable types ensure that their values remain constant throughout the program, reducing bugs and unexpected behavior.
#code
# Immutable types
x = 10
x = 20 # This creates a new integer object, x now refers to the new object
name = "Alice"
name = "Bob" # This creates a new string object, name now refers to the new object
is_active = True
is_active = False # This creates a new boolean object, name now refers to the new object
Mutable Types:
- Flexibility: Mutable types can be modified in place, allowing changes to their state without creating new objects.
- Use Cases: They are used for collections of items where elements need to be added, removed, or changed.
#code
# Mutable types
numbers = [1, 2, 3]
numbers.append(4) # Modifies the list in place
fruits = {"apple", "banana"}
fruits.add("cherry") # Modifies the set in place
person = {"name": "Alice", "age": 30}
person["age"] = 31 # Modifies the dictionary in place
Modifying Mutable Types Inside Functions:
- When mutable objects are passed to a function, changes made to the object inside the function are reflected outside the function.
#code
def modify_list(lst):
lst.append(4)
print("Inside function:", lst)
my_list = [1, 2, 3]
modify_list(my_list)
print("Outside function:", my_list)
# Output:
# Inside function: [1, 2, 3, 4]
# Outside function: [1, 2, 3, 4]
Implications of Passing Mutable Objects to Functions:
- Passing mutable objects to functions allows for in-place modification, which can be both powerful and risky.
- Ensure that modifications to mutable objects are intentional to avoid unintended side effects.
#code
def modify_dict(d):
d["new_key"] = "new_value"
print("Inside function:", d)
my_dict = {"key": "value"}
modify_dict(my_dict)
print("Outside function:", my_dict)
# Output:
# Inside function: {'key': 'value', 'new_key': 'new_value'}
# Outside function: {'key': 'value', 'new_key': 'new_value'}
This chapter introduces the fundamental concepts of time and space complexity, explaining why they are critical in algorithm analysis. You'll learn about Big 'O' notation, constant space and time complexity, and how to analyze the complexity of a basic algorithm like linear search.
Why Do We Need Time and Space Complexity?
- Understanding time and space complexity helps in selecting and designing efficient algorithms, particularly for large inputs. This ensures optimal use of resources and faster execution times.
- Efficient algorithms can significantly reduce processing time and memory usage, which is crucial in fields like data processing, web development, and artificial intelligence.
Big 'O' Notation:
- A mathematical notation that describes the upper bound of an algorithm’s time or space complexity, giving a high-level understanding of its performance.
Common Big-O Notations:
- O(1): Constant time/space complexity. Example: Accessing an element in an array.
- O(N): Linear time/space complexity. Example: Iterating through a list.
- O(N^2): Quadratic time/space complexity. Example: Nested loops.
- O(log N): Logarithmic time/space complexity. Example: Binary search.
- O(N log N): Linearithmic time/space complexity. Example: Merge sort.
Constant Space and Time Complexity:
- An algorithm is said to have constant time complexity if it takes the same amount of time regardless of the input size.
Example: Accessing an element in an array by index.
Constant Space Complexity (O(1)):
- An algorithm is said to have constant space complexity if it uses a fixed amount of memory regardless of the input size.
Example: A function that swaps two variables using temporary storage.
Linear Search - Space and Time Complexity:
- A simple search algorithm that checks each element in a list sequentially until the target element is found or the list ends.
Time Complexity of Linear Search:
- Best Case (O(1)): The target element is at the first position.
- Average Case (O(N/2)): On average, the target element is found halfway through the list.
- Worst Case (O(N)): The target element is at the last position or not present in the list.
Space Complexity of Linear Search:
O(1): Linear search uses a constant amount of extra space regardless of the input size.
#code
def linear_search(arr, target):
for index in range(len(arr)):
if arr[index] == target:
return index
return -1
# Example usage
numbers = [4, 2, 9, 7, 3, 6]
target = 7
result = linear_search(numbers, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
In this chapter, we delve into the methods of calculating time complexities for various types of algorithms. You'll learn how to analyze the time complexity of nested loops, sequential loops, and parallel loops. We'll also cover how to simplify complexities by removing constants and focusing on the dominant terms, including more examples and complex scenarios.
Introduction to Calculating Time Complexities:
- Purpose: Understanding how to calculate time complexity is crucial for evaluating the efficiency of an algorithm.
- Importance: Helps in comparing algorithms and choosing the most efficient one for a given problem.
Single Loop:
#code
for i in range(n):
# constant time operation
print(i)
- Time Complexity: O(n)
- Explanation: The loop runs n times, performing a constant time operation in each
iteration.
Nested Loops:
#code
for i in range(n):
for j in range(n):
# constant time operation
print(i, j)
- Time Complexity: O(n^2)
- Explanation: The outer loop runs n times, and for each iteration of the outer loop, the inner loop runs n times.
#code
for i in range(n):
for j in range(m):
# constant time operation
print(i, j)
- Time Complexity: O(n * m)
- Explanation: The outer loop runs n times and the inner loop runs m times for each iteration of the outer loop.
Parallel Loops:
#code
for i in range(n):
# constant time operation
print(i)
for j in range(n):
# constant time operation
print(j)
- Time Complexity: O(n) + O(n) = O(n)
- Explanation: Each loop runs n times independently. The total time complexity is the sum, but since both are O(n), it simplifies to O(n).
Removing Constants:
#code
for i in range(n):
for j in range(100):
# constant time operation
print(i, j)
- Time Complexity: O(n * 100) = O(n)
- Explanation: The inner loop runs a constant 100 times, which simplifies to O(n).
Considering Dominant Terms:
#code
for i in range(n):
for j in range(n):
# constant time operation
print(i, j)
for k in range(n):
# constant time operation
print(k)
- Time Complexity: O(n^2) + O(n) = O(n^2)
- Explanation: The O(n^2) term dominates the O(n) term, so the overall complexity is O(n^2).
Complex Scenarios:
Nested Loops with Different Ranges:
#code
for i in range(n):
for j in range(m):
# constant time operation
print(i, j)
- Time Complexity: O(n * m)
- Explanation: The outer loop runs n times and the inner loop runs m times for each iteration of the outer loop.
Loop with Logarithmic Complexity:
#code
i = 1
while i < n:
# constant time operation
print(i)
i *= 2
- Time Complexity: O(log n)
- Explanation: The loop variable i is doubled each time, resulting in a logarithmic number of iterations.
Complex Nested Loops:
#code
for i in range(n):
for j in range(n):
for k in range(n):
# constant time operation
print(i, j, k)
- Time Complexity: O(n^3)
- Explanation: Three nested loops each running n times.
#code
for i in range(n):
for j in range(i):
# constant time operation
print(i, j)
- Time Complexity: O(n^2)
- Explanation: The outer loop runs n times, and the inner loop runs up to i times, resulting in a triangular number of iterations, which simplifies to O(n^2).
Example with Multiple Functions:
Function Calls:
#code
def foo(n):
for i in range(n):
bar(n)
def bar(n):
for j in range(n):
# constant time operation
print(j)
- Time Complexity: O(n) * O(n) = O(n^2)
- Explanation: The foo function calls bar n times, and each call to bar runs n times.
In this chapter, we will delve into the time and space complexity associated with various operations (insertion, deletion, searching, and updating) for common data structures such as arrays, lists, sets, and dictionaries. Understanding these complexities is crucial for making informed decisions about which data structures to use in different scenarios, thereby optimizing the performance of your algorithms.
In this chapter, we focus on solving some of the most basic yet fundamental problems in programming. We will cover:
Even or Odd Number: Learn how to check if a number is even or odd using basic arithmetic operations.
Sum of Digits of a Number: Understand how to break down a number to calculate the sum of its digits.
Largest Element in a List: Explore how to iterate through a list to find the largest element.
Factorial of a Number: Discover how to calculate the factorial of a number using iterative method.
These problems are designed to reinforce basic logic and coding skills, providing a solid foundation for more complex problem-solving.
Even or Odd Number
#code
def check_even_odd(number):
if number % 2 == 0:
return f"{number} is even."
else:
return f"{number} is odd."
print(check_even_odd(10)) # Output: 10 is even.
print(check_even_odd(7)) # Output: 7 is odd.
Sum of Digits of a Number
#code
def sum_of_digits(number):
total = 0
while number > 0:
total += number % 10
number //= 10
return total
print(sum_of_digits(123)) # Output: 6 (1+2+3)
print(sum_of_digits(4567)) # Output: 22 (4+5+6+7)
Largest Element in a List
#code
def find_largest_element(lst):
if not lst:
return None
largest = lst[0]
for num in lst:
if num > largest:
largest = num
return largest
print(find_largest_element([3, 7, 2, 9, 4])) # Output: 9
print(find_largest_element([10, 22, 5, 75, 65])) # Output: 75
Factorial of a Number
#code
def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial_iterative(5)) # Output: 120 (5*4*3*2*1)
print(factorial_iterative(7)) # Output: 5040 (7*6*5*4*3*2*1)
In this chapter, we delve into two important concepts in mathematics and programming: Greatest Common Divisor (GCD) and Least Common Multiple (LCM). We will explore what they are, how they relate to each other, and how to compute them efficiently using different methods.
- The GCD of two numbers is the largest number that divides both of them without leaving a remainder.
#code
def gcd(a, b):
while b:
a, b = b, a % b
return a
print(gcd(54, 24)) # Output: 6
print(gcd(48, 18)) # Output: 6
Using Python's Built-in Function (if available):
#code
import math
print(math.gcd(54, 24)) # Output: 6
print(math.gcd(48, 18)) # Output: 6
LCM (Least Common Multiple)
- The LCM of two numbers is the smallest number that is a multiple of both of them.
Using the Relationship between GCD and LCM:
LCM(?,?) = ∣?×?∣ / GCD(?,?)
#code
def lcm(a, b):
return abs(a * b) // gcd(a, b)
print(lcm(54, 24)) # Output: 216
print(lcm(48, 18)) # Output: 144
Key Takeaways:
- GCD helps in simplifying fractions, finding common denominators, and solving problems involving divisibility.
- LCM is useful in problems involving synchronization, scheduling, and finding common time intervals.
In this chapter, we dive into the concept of prime numbers and explore efficient algorithms to determine if a number is prime, sum all prime numbers up to a given number n, and find all primes up to n. We start by understanding the time complexity of checking for prime numbers in O(n) and extend this knowledge to solve related problems. The chapter includes practical coding examples to demonstrate these concepts, ensuring you grasp both the theoretical and practical aspects of prime number calculations.
1. Checking if a Number is Prime in O(n) Time Complexity.
- To check whether a number n is prime, you only need to test for divisibility up to n.
If n is divisible by any number other than 1 and itself, it is not prime.
# code
def is_prime(n):
if n <= 1:
return False
for i in range(2, n + 1):
if n%i==0:
return False
return True
- Now instead of running this loop till O(n), use O(root(n)).
# code
import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n%i==0:
return False
return True
2. Sum of Prime Numbers up to n
- This problem requires summing all prime numbers up to a given number n. We can use the is_prime function from above to check each number up to n and sum the primes.
# code
def sum_of_primes(n):
prime_sum = 0
for i in range(2, n + 1):
if is_prime(i):
prime_sum += i
return prime_sum
3. Finding All Prime Numbers Up to n (Optimal Approach)
- To find all prime numbers up to n, the Sieve of Eratosthenes algorithm is the most efficient, with a time complexity of O(nloglogn).
# code
def sieve_of_eratosthenes(n):
primes = [True] * (n + 1)
p = 2
while p * p <= n:
if primes[p] == True:
for i in range(p * p, n + 1, p):
primes[i] = False
p += 1
return prime_numbers
sieve_of_eratosthenes(n): This function efficiently finds all prime numbers up to n using the sieve method, marking multiples of each prime starting from 2. The time complexity is O(nloglogn), which is optimal for generating a list of primes.
In this chapter, we explore two fascinating types of numbers: palindromes and Armstrong numbers. A palindrome is a number that reads the same backward as forward, and understanding how to identify such numbers is a key concept in many coding challenges. We will learn how to implement algorithms to check if a given number is a palindrome.
# code
def is_palindrome(num):
original_num = num
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
return original_num == reversed_num
# Example Usage:
num = 121
if is_palindrome(num):
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
# code
def is_armstrong(num):
digits = list(map(int, str(num)))
power = len(digits)
sum_of_powers = sum(digit ** power for digit in digits)
return sum_of_powers == num
# Example Usage:
num = 153
if is_armstrong(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
# code
def print_square_pattern(n):
for i in range(n):
for j in range(n):
print('*', end='')
print()
# Example Usage:
n = 5
print_square_pattern(n)
# code
def print_right_angled_triangle(n):
for i in range(1, n + 1):
for j in range(i):
print('*', end='')
print()
def print_number_triangle(n):
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end=' ')
print()
# Example Usage:
n = 5
print_right_angled_triangle(n)
print_number_triangle(n)
# code
def print_inverted_triangle(n):
for i in range(n, 0, -1):
for j in range(i):
print('*', end='')
print()
def print_inverted_number_triangle(n):
for i in range(n, 0, -1):
for j in range(1, i + 1):
print(j, end=' ')
print()
def print_repeated_number_triangle(n):
for i in range(1, n + 1):
for j in range(i):
print(i, end=' ')
print()
# Example Usage:
n = 5
print_inverted_triangle(n)
print_inverted_number_triangle(n)
print_repeated_number_triangle(n)
In this chapter, we explore three fundamental sorting algorithms: Selection Sort, Insertion Sort, and Bubble Sort. These algorithms serve as the building blocks for understanding more advanced sorting techniques. We'll discuss their implementation, how they work, and their respective time complexities.
Selection Sort
- Selection Sort repeatedly selects the smallest element from the unsorted portion of the list and swaps it with the first unsorted element. It continues this process until the list is sorted.
# code
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
# Example Usage:
arr = [64, 25, 12, 22, 11]
selection_sort(arr)
print("Sorted array:", arr)
Time Complexity:
Best Case: O(n*n)
Average Case: O(n*n)
Worst Case: O(n*n)
Insertion Sort
- Insertion Sort builds the sorted array one element at a time. It takes each element from the unsorted part and inserts it into its correct position within the sorted part.
# code
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Example Usage:
arr = [64, 25, 12, 22, 11]
insertion_sort(arr)
print("Sorted array:", arr)
Time Complexity:
Best Case: O(n)
Average Case: O(n*n)
Worst Case: O(n*n)
Bubble Sort
- Bubble Sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped:
break
# Example Usage:
arr = [64, 25, 12, 22, 11]
bubble_sort(arr)
print("Sorted array:", arr)
Time Complexity:
Best Case: O(n)
Average Case: O(n*n)
Worst Case: O(n*n)
Selection Sort selects the minimum element and swaps it with the first unsorted element.
Insertion Sort inserts elements into their correct position within the sorted portion.
Bubble Sort repeatedly swaps adjacent elements to "bubble" the largest unsorted element to its correct position.
Here we will be solving some questions using list, set, dictionaries.
In this chapter, we will cover different techniques for finding the maximum and second maximum elements in a list. We will compare methods such as using simple loops, sorting, and built-in functions. Additionally, we will discuss the drawbacks of sorting for finding the second maximum element, particularly when dealing with repeated values. We will also explore how to efficiently find the frequency of each element using dictionaries.
Finding the Maximum Element
- Using Simple Loop
# code
def find_max_element(lst):
max_elem = lst[0]
for elem in lst:
if elem > max_elem:
max_elem = elem
return max_elem
# Example Usage
lst = [1, 2, 3, 4, 5]
max_element = find_max_element(lst)
print(max_element) # Output: 5
- Using Sorting
# code
def find_max_element_sorted(lst):
lst.sort()
return lst[-1]
# Example Usage
lst = [1, 2, 3, 4, 5]
max_element = find_max_element_sorted(lst)
print(max_element) # Output: 5
- Using Built-in max Function
# code
def find_max_element_max(lst):
return max(lst)
# Example Usage
lst = [1, 2, 3, 4, 5]
max_element = find_max_element_max(lst)
print(max_element) # Output: 5
Finding the Second Maximum Element
- Using Loop
# code
def find_second_max_element(lst):
if len(lst) < 2:
return None # Not enough elements to find the second maximum
first_max = second_max = float('-inf')
for elem in lst:
if elem > first_max:
second_max = first_max
first_max = elem
elif first_max > elem > second_max:
second_max = elem
return second_max if second_max != float('-inf') else None
# Example Usage
lst = [1, 2, 3, 4, 5]
second_max_element = find_second_max_element(lst)
print(second_max_element) # Output: 4
Finding Frequency of Each Element
- Using Dictionary
# code
def find_frequency(lst):
frequency = {}
for elem in lst:
if elem in frequency:
frequency[elem] += 1
else:
frequency[elem] = 1
return frequency
# Example Usage
lst = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
frequency = find_frequency(lst)
print(frequency) # Output: {1: 1, 2: 2, 3: 3, 4: 4}
Summary:
- Finding the maximum element is efficiently achieved using a loop or built-in functions.
- The second maximum element is best found using a loop due to its O(n) time complexity, whereas sorting is less efficient.
- Frequency analysis using a dictionary is an efficient way to count occurrences, with O(n) time complexity and O(n) space complexity.
In this chapter, we will explore methods to calculate the mean, median, and mode of a list. We will cover how to achieve these calculations using sorting and dictionaries, providing clear examples and code for each approach.
Mean
- Using Simple Loop
# code
def calculate_mean(lst):
return sum(lst) / len(lst) if lst else 0
# Example Usage
lst = [1, 2, 3, 4, 5]
mean = calculate_mean(lst)
print(mean) # Output: 3.0
Median
- Using Sorting
# code
def calculate_median(lst):
lst.sort()
n = len(lst)
mid = n // 2
if n % 2 == 0:
return (lst[mid - 1] + lst[mid]) / 2
else:
return lst[mid]
# Example Usage
lst = [1, 2, 3, 4, 5]
median = calculate_median(lst)
print(median) # Output: 3
lst_even = [1, 2, 3, 4]
median_even = calculate_median(lst_even)
print(median_even) # Output: 2.5
Mode
- Using Dictionary
def calculate_mode(lst):
frequency = {}
for elem in lst:
if elem in frequency:
frequency[elem] += 1
else:
frequency[elem] = 1
max_freq = max(frequency.values())
modes = [key for key, value in frequency.items() if value == max_freq]
return modes
# Example Usage
lst = [1, 2, 3, 3, 4, 4, 4]
mode = calculate_mode(lst)
print(mode) # Output: [4]
Summary:
- Mean is calculated using a simple loop to sum the elements and divide by the number of elements.
- Median can be found by sorting the list and selecting the middle element(s), with different handling for odd and even-length lists.
- Mode is determined using a dictionary to count occurrences and then identifying the value(s) with the highest frequency.
In this chapter, we will cover techniques for reversing a list and solving pair problems with a given sum using two pointers, hash tables, and sorting. We will discuss how the two-pointer technique works, how to detect problems suitable for this method, and provide code examples for finding pairs with a given sum.
Reversing a List
- Using Two Pointers
-- The two-pointer technique involves using two pointers, typically starting from opposite ends of the list, and moving towards each other. This method is effective for problems involving linear traversal with a need for element swapping or comparison.
# code
def reverse_list(lst):
start, end = 0, len(lst) - 1
while start < end:
lst[start], lst[end] = lst[end], lst[start]
start += 1
end -= 1
return lst
# Example Usage
lst = [1, 2, 3, 4, 5]
reversed_lst = reverse_list(lst)
print(reversed_lst) # Output: [5, 4, 3, 2, 1]
Using reverse() Function:
# code
def reverse_list_builtin(lst):
lst.reverse()
return lst
# Example Usage
lst = [1, 2, 3, 4, 5]
reversed_lst = reverse_list_builtin(lst)
print(reversed_lst) # Output: [5, 4, 3, 2, 1]
Two Pointer Technique
- The two-pointer technique involves using two indices (or pointers) that traverse the data structure from different directions or at different speeds. It is often used for problems involving sorted arrays, subarrays, or sequences where comparisons or operations are needed.
Detecting Suitable Problems:
- Problems involving pairs or subarrays where elements need to be compared or manipulated in pairs.
- Problems where the data structure is sorted or can be sorted to facilitate efficient traversal.
Finding a Pair with a Given Sum
- Using Hash Table
# code
def find_pair_with_sum_hash(lst, target_sum):
seen = set()
for num in lst:
complement = target_sum - num
if complement in seen:
return (complement, num)
seen.add(num)
return None
# Example Usage
lst = [2, 4, 7, 11, 15]
target_sum = 9
pair = find_pair_with_sum_hash(lst, target_sum)
print(pair) # Output: (4, 5) or (5, 4)
Using Sorting and Two Pointers
# code
def find_pair_with_sum_two_pointers(lst, target_sum):
lst.sort()
left, right = 0, len(lst) - 1
while left < right:
current_sum = lst[left] + lst[right]
if current_sum == target_sum:
return (lst[left], lst[right])
elif current_sum < target_sum:
left += 1
else:
right -= 1
return None
# Example Usage
lst = [2, 4, 7, 11, 15]
target_sum = 9
pair = find_pair_with_sum_two_pointers(lst, target_sum)
print(pair) # Output: (4, 5) or (5, 4)
Finding Index of Pair with Given Sum
- Using Hash Table
# code
def find_pair_indices_with_sum_hash(lst, target_sum):
index_map = {}
for i, num in enumerate(lst):
complement = target_sum - num
if complement in index_map:
return (index_map[complement], i)
index_map[num] = i
return None
# Example Usage
lst = [2, 4, 7, 11, 15]
target_sum = 9
indices = find_pair_indices_with_sum_hash(lst, target_sum)
print(indices) # Output: (1, 2) where 2 + 7 = 9
Using Sorting and Two Pointers
# code
def find_pair_indices_with_sum_two_pointers(lst, target_sum):
sorted_indices = sorted(range(len(lst)), key=lambda i: lst[i])
left, right = 0, len(lst) - 1
while left < right:
current_sum = lst[sorted_indices[left]] + lst[sorted_indices[right]]
if current_sum == target_sum:
return (sorted_indices[left], sorted_indices[right])
elif current_sum < target_sum:
left += 1
else:
right -= 1
return None
# Example Usage
lst = [2, 4, 7, 11, 15]
target_sum = 9
indices = find_pair_indices_with_sum_two_pointers(lst, target_sum)
print(indices) # Output: (1, 2) where 2 + 7 = 9
Summary:
- Reversing a List can be achieved using the two-pointer technique or Python’s built-in reverse() function.
- Two-pointer technique is useful for problems where traversal and comparison of elements are required.
- Finding pairs with a given sum can be done efficiently using hash tables or sorting combined with the two-pointer technique.
- Finding the indices of such pairs can also be efficiently handled using hash tables or sorted indices with two pointers.
In this chapter, we will tackle three problems: sorting an array containing two colors (0 and 1), sorting an array with three colors (0, 1, 2), and finding the maximum number of consecutive ones in a list containing only 0s and 1s. These problems will help reinforce the application of sorting and the two-pointer technique.
Problem 1: Sort Array with Two Colors (0 and 1)
- Approach: Two Pointers
We can use the two-pointer technique to sort an array containing only 0s and 1s. One pointer starts from the beginning of the array and the other from the end. The idea is to move all the 0s to the left and all the 1s to the right.
# code
def sort_colors_two(lst):
left, right = 0, len(lst) - 1
while left < right:
if lst[left] == 1 and lst[right] == 0:
lst[left], lst[right] = lst[right], lst[left]
if lst[left] == 0:
left += 1
if lst[right] == 1:
right -= 1
return lst
# Example Usage
lst = [0, 1, 1, 0, 1, 0]
sorted_lst = sort_colors_two(lst)
print(sorted_lst) # Output: [0, 0, 0, 1, 1, 1]
Problem 2: Sort Array with Three Colors (0, 1, 2)
- Approach: Dutch National Flag Problem
We can extend the two-pointer approach to sort an array with three colors (0, 1, 2). Here, we use three pointers: low, mid, and high. The low pointer handles 0s, high handles 2s, and mid traverses the array.
# code
def sort_colors_three(lst):
low, mid, high = 0, 0, len(lst) - 1
while mid <= high:
if lst[mid] == 0:
lst[low], lst[mid] = lst[mid], lst[low]
low += 1
mid += 1
elif lst[mid] == 1:
mid += 1
else:
lst[mid], lst[high] = lst[high], lst[mid]
high -= 1
return lst
# Example Usage
lst = [2, 0, 2, 1, 1, 0]
sorted_lst = sort_colors_three(lst)
print(sorted_lst) # Output: [0, 0, 1, 1, 2, 2]
Problem 3: Maximum Consecutive Ones in a List
- Approach: Single Pass with a Counter
To find the maximum number of consecutive 1s in a list of 0s and 1s, we can traverse the list once, counting the current streak of 1s and updating the maximum streak when a 0 is encountered.
# code
def max_consecutive_ones(lst):
max_count = 0
current_count = 0
for num in lst:
if num == 1:
current_count += 1
max_count = max(max_count, current_count)
else:
current_count = 0
return max_count
# Example Usage
lst = [1, 1, 0, 1, 1, 1, 0, 1]
max_ones = max_consecutive_ones(lst)
print(max_ones) # Output: 3
Summary:
- Sort Array with Two Colors: Use the two-pointer technique to sort an array of 0s and 1s efficiently.
- Sort Array with Three Colors: Apply the Dutch National Flag algorithm with three pointers to sort an array with 0s, 1s, and 2s.
- Maximum Consecutive Ones: Traverse the array once to find the maximum number of consecutive 1s, keeping track of the current streak and updating the maximum count.
In this chapter, we will explore the problem of finding the longest substring without repeating characters. We'll introduce the sliding window technique, discuss when and where it is useful, and explain the difference between the sliding window and the two-pointer technique. You’ll also see how to implement this using an efficient approach with an example.
Sliding Window Technique
What is Sliding Window?
- The sliding window technique is a method used to solve problems that involve a subset or subarray of a given size that slides across the array or string. The "window" can either be of fixed size or variable size, and it "slides" over the data to examine subsets of elements at a time. This technique is particularly useful for problems involving subarrays or substrings, where the focus is on a continuous block of elements.
When and Where to Use Sliding Window:
- When you need to find a subarray or substring that meets certain conditions (e.g., maximum sum, longest substring, etc.).
- When the problem involves contiguous elements.
- When you need to reduce the time complexity by avoiding nested loops.
Difference Between Sliding Window and Two Pointers
Sliding Window vs. Two Pointers:
- Sliding Window: Focuses on a "window" of elements that changes in size or position to solve problems involving subarrays or substrings. The window expands or contracts as needed.
- Two Pointers: Involves two indices that traverse the data structure, typically from different directions or at different speeds, without necessarily focusing on a contiguous subset. It’s often used for sorting, searching, or pairing problems.
Problem: Find Longest Substring Without Repeating Characters
Approach: Sliding Window
- To find the longest substring without repeating characters, we can use a sliding window. We maintain a window that expands by adding characters from the string until a duplicate is found. When a duplicate is found, we shrink the window from the left until the duplicate is removed, then continue expanding.
name = "lmabcabcdbcef"
n = len(name)
s, e = 0, 0
freq = {}
ans = 0
ansS = 0
ansE = 0
while e < n:
ch = name[e]
freq[ch] = freq.get(ch, 0) + 1
# Check if the window is valid (no repeating characters)
if e - s + 1 == len(freq):
if e - s + 1 > ans:
ans = e - s + 1
ansS = s
ansE = e
e += 1
else:
# Contract the window until it's valid again
while s < e and e - s + 1 != len(freq):
ch = name[s]
freq[ch] -= 1
if freq[ch] == 0:
del freq[ch]
s += 1
e += 1
print(ans, ansS, ansE) # Output: 4 7 10 (The longest substring is "bcdb" with length 4)
Summary:
- Sliding Window Technique helps solve problems involving subarrays or substrings by maintaining a dynamic window over the elements.
- Difference Between Sliding Window and Two Pointers: Sliding window focuses on a contiguous block of elements, while two pointers are more general, often used for pairing or comparison tasks.
- Longest Substring Without Repeating Characters: Use the sliding window technique with a frequency dictionary to dynamically adjust the window size to find the longest substring where no characters repeat.
In this chapter, we introduce Classes and Objects, the foundation of Object-Oriented Programming (OOP) in Python. A class is a blueprint for creating objects, and an object is an instance of a class. This chapter covers how to define classes, create objects, and access attributes and methods of a class.
# code
class Car:
# Constructor to initialize attributes
def __init__(self, make, model):
self.make = make # Instance variable
self.model = model
# Method to display car details
def display(self):
print(f"Car Make: {self.make}, Model: {self.model}")
# Create an object (instance) of the Car class
car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Civic")
# Access attributes and methods
car1.display() # Output: Car Make: Toyota, Model: Corolla
car2.display() # Output: Car Make: Honda, Model: Civic
Key Concepts Covered:
Class:
- Defined using the class keyword.
- Contains attributes (variables) and methods (functions) to define behavior.
Object:
- Created by instantiating a class.
- Represents an individual entity based on the class blueprint.
Constructor:
- Defined using __init__ to initialize the attributes of an object.
Attributes and Methods:
- Attributes: Variables that hold data specific to an object.
- Methods: Functions that define the behavior of the objects.
In this chapter, we apply the concepts of classes and objects through practical examples. We will explore real-world scenarios, write Python programs to solve them using classes, and demonstrate the use of attributes, methods, and constructors.
Practical Example 1: Student Management System
Problem:
- Create a class Student to manage student information, including name, roll number, and marks. Implement methods to calculate the average marks and display student details.
# code
class Student:
def __init__(self, name, roll_no, marks):
self.name = name
self.roll_no = roll_no
self.marks = marks # List of marks in different subjects
def calculate_average(self):
return sum(self.marks) / len(self.marks)
def display_details(self):
print(f"Name: {self.name}, Roll No: {self.roll_no}")
print(f"Marks: {self.marks}")
print(f"Average Marks: {self.calculate_average():.2f}")
# Create student objects
student1 = Student("Alice", 101, [85, 90, 88])
student2 = Student("Bob", 102, [78, 82, 80])
# Display details
student1.display_details()
student2.display_details()
Practical Example 2: Bank Account
Problem:
- Create a class BankAccount to manage account details like balance, deposit, and withdrawal operations.
# code
class BankAccount:
def __init__(self, account_number, account_holder, balance=0):
self.account_number = account_number
self.account_holder = account_holder
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited {amount}. New Balance: {self.balance}")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient balance!")
else:
self.balance -= amount
print(f"Withdrew {amount}. Remaining Balance: {self.balance}")
def display_balance(self):
print(f"Account Holder: {self.account_holder}, Balance: {self.balance}")
# Create a bank account object
account = BankAccount("123456789", "John Doe", 500)
# Perform transactions
account.deposit(200)
account.withdraw(100)
account.display_balance()
Key Takeaways:
- Practical applications reinforce the use of classes and objects in solving real-world problems.
- By working on examples like Student Management and Bank Account, you understand how to design and implement classes with appropriate attributes and methods.
In this chapter, we focus on instance attributes and instance methods, which are unique to each object created from a class. Instance attributes store data specific to an object, while instance methods operate on these attributes to define the object's behavior.
Key Concepts:
Instance Attributes:
- Attributes that belong to a specific object.
- Defined within the __init__ constructor using self.
Instance Methods:
- Functions that operate on instance attributes.
- Always take self as the first parameter to access the object’s data.
# code
class Employee:
def __init__(self, name, salary):
# Instance attributes
self.name = name
self.salary = salary
# Instance method to display details
def display_details(self):
print(f"Employee Name: {self.name}")
print(f"Salary: {self.salary}")
# Instance method to give a raise
def give_raise(self, amount):
self.salary += amount
print(f"{self.name} got a raise! New Salary: {self.salary}")
# Create objects
emp1 = Employee("Alice", 50000)
emp2 = Employee("Bob", 60000)
# Access and modify instance attributes through methods
emp1.display_details()
emp1.give_raise(5000)
emp2.display_details()
emp2.give_raise(7000)
Key Takeaways:
- Instance attributes ensure each object has its own unique data.
- Instance methods provide a way to interact with and modify an object's attributes.
- Understanding these concepts is crucial for designing reusable and modular classes.
In this chapter, we explore class variables and class methods, which are shared across all instances of a class. Class variables store data common to all objects, and class methods operate on these shared attributes using the @classmethod decorator.
Key Concepts:
Class Variables:
- Declared inside the class but outside any methods.
- Shared by all instances of the class.
- Changes made to class variables affect all instances.
Class Methods:
- Defined using the @classmethod decorator.
- Take cls as the first parameter to access and modify class-level data.
- Operate on class variables rather than instance-specific attributes.
# code
class Employee:
# Class variable
company_name = "TechCorp"
employee_count = 0
def __init__(self, name, salary):
self.name = name # Instance attribute
self.salary = salary # Instance attribute
Employee.employee_count += 1 # Update class variable
# Instance method to display details
def display_details(self):
print(f"Employee Name: {self.name}, Salary: {self.salary}")
# Class method to get the total number of employees
@classmethod
def get_employee_count(cls):
return f"Total Employees: {cls.employee_count}"
# Class method to update the company name
@classmethod
def update_company_name(cls, new_name):
cls.company_name = new_name
# Create objects
emp1 = Employee("Alice", 50000)
emp2 = Employee("Bob", 60000)
# Access class method
print(Employee.get_employee_count()) # Output: Total Employees: 2
# Access and modify class variable through a class method
Employee.update_company_name("NextGenTech")
print(f"Updated Company Name: {Employee.company_name}")
Key Takeaways:
- Class variables store data shared among all objects and can be accessed using cls in class methods.
- Class methods provide functionality at the class level, independent of specific objects.
- Class-level operations ensure efficient handling of shared data and collective updates.
This chapter provides an overview of the topics covered in this module, including Kadane's Algorithm, prefix sum problems, sliding window techniques, and solving complex problems using frequency dictionaries and prefix sums.
Learn how to find the maximum sum of a contiguous subarray efficiently using Kadane's Algorithm. This technique uses dynamic programming to keep track of the maximum sum ending at each position and the overall maximum sum encountered so far.
Key Points:
- Iteratively compute the sum of the current subarray (curr) and update the maximum sum (ans).
- Use the max() function to decide whether to continue the current subarray or start a new one.
- Achieves optimal time complexity of O(n).
# code
class Solution:
# Function to find the sum of contiguous subarray with maximum sum.
def maxSubArraySum(self, arr):
pre = arr[0]
ans = arr[0]
n = len(arr)
for i in range(1, n):
curr = max(arr[i] + pre, arr[i])
ans = max(ans, curr)
pre = curr
return ans
What You Will Learn:
- Efficiently solving the maximum subarray sum problem.
- Using dynamic programming principles in real-world problems.
- Building a foundation for solving advanced array-related problems.
This chapter focuses on the prefix sum technique, a powerful method used for quickly calculating sums of subarrays in constant time after an O(n) preprocessing step. By maintaining a prefix array where each element represents the sum of all previous elements, you can answer range-sum queries efficiently.
Key Points:
Prefix Array Construction:
- Create an array pre of length n+1 (if the original array has n elements).
- Set pre[0] = 0.
- For each index i in arr, compute pre[i+1] = pre[i] + arr[i].
Range Sum Query:
- To find the sum of elements from index l to r, use: sum=pre[r+1]−pre[l]
Time Complexity:
- Preprocessing: O(n) to build the prefix sum array.
- Querying: O(1) per range sum query.
# code
arr = [3, 1, 5, 7, 9, 2]
n = len(arr)
# Step 1: Construct prefix sum array
pre = [0] * (n + 1)
for i in range(n):
pre[i + 1] = arr[i] + pre[i]
print("Original Array:", arr)
print("Prefix Sum Array:", pre)
# Step 2: Sample query for sum of elements from index l to r
l = 0
r = 3
ans = pre[r + 1] - pre[l]
print(f"Sum of elements from index {l} to {r}:", ans)
What You Will Learn:
- How to build a prefix sum array to enable constant-time range queries.
- Practical usage of prefix sums in solving problems like subarray sums, range update queries, and more.
- Importance of preprocessing to optimize queries in data structures.
In this chapter, you will learn how to find the longest subarray whose elements sum up to a given target k using a sliding window approach. By dynamically adjusting the window's boundaries based on the current sum compared to k, you can efficiently track subarray lengths that match the desired sum.
Key Points:
- Sliding Window Technique:
- Maintain two pointers (s for start and e for end) and a running sum (sm).
- Expand the window by moving e to the right, and shrink it by moving s to the right
if the running sum exceeds k.
- Time Complexity:
- O(n), where n is the number of elements. Each element is visited at most twice
(once when expanding the window, once when shrinking).
- Edge Cases:
- When k = 0, ensure handling zero or negative values in the array.
- If no subarray sums to k, the result remains 0.
# code
def longestSubarrayWithSumK(arr: [int], k: int) -> int:
s, e = 0, 0
n = len(arr)
sm = 0
ans = 0
while e < n:
sm += arr[e] # expand window to the right
# If current sum is less than k, just move 'e' forward
if sm < k:
e += 1
# If current sum exceeds k, shrink from the left
elif sm > k:
while s <= e and sm > k:
sm -= arr[s]
s += 1
# Check if sum equals k after shrinking
if sm == k:
ans = max(ans, e - s + 1)
e += 1
# If current sum equals k
else:
ans = max(ans, e - s + 1)
e += 1
return ans
In this chapter, you will learn how to find the longest substring of a given string that does not contain any repeating characters. The approach uses a sliding window combined with a frequency dictionary to keep track of the characters in the current window.
Key Points:
- Sliding Window Approach:
- Maintain two pointers (s for start and e for end) that define the current substring.
- Expand the window (e++) while ensuring no repeated characters exist.
- If a character repeats, shrink from the left by moving s until the substring has all
unique characters.
- Frequency Dictionary:
- A dictionary (dp) stores the frequency of each character in the current window.
- If dp’s size matches the window length (e - s + 1), it indicates all characters are
unique.
- Time Complexity:
- O(n) where n is the length of the string. Each character is visited at most twice
(once when expanding the window, once when shrinking).
- Edge Cases:
- An empty string returns 0.
- Strings with all identical characters have a maximum length of 1.
- Very long strings may require careful handling to avoid timeouts in lower-level
languages, but in Python the approach still works within the constraints.
# code
class Solution:
def lengthOfLongestSubstring(self, name: str) -> int:
s, e = 0, 0
n = len(name)
dp = {}
ans = 0
while e < n:
# Add the current character to the frequency dictionary
ch = name[e]
dp[ch] = dp.get(ch, 0) + 1
# If the window size equals the number of distinct characters, update ans
if (e - s + 1) == len(dp):
ans = max(ans, e - s + 1)
e += 1
else:
# Shrink from the left until the window has all unique characters
while s <= e and (e - s + 1) != len(dp):
left_char = name[s]
if dp[left_char] > 1:
dp[left_char] -= 1
else:
del dp[left_char]
s += 1
# Update ans after shrinking
if (e - s + 1) == len(dp):
ans = max(ans, e - s + 1)
e += 1
return ans
What You Will Learn:
- Sliding Window and Dictionary: How to track character frequencies in real time to
enforce uniqueness in the substring.
- Window Adjustment: Techniques to expand or shrink the window to find the
desired property (all unique characters).
- Optimization: Balancing time complexity by moving each pointer at most once
across the string.
In this chapter, we focus on finding the longest subarray of 1s after flipping at most k zeros to ones in a binary array. The solution utilizes a sliding window technique and a dictionary to keep track of the frequency of elements (particularly zeros). The window dynamically expands and shrinks to maintain a state where the number of flipped zeros does not exceed k.
# code
class Solution:
def isValid(self, dp, k):
return dp.get(0, 0) <= k
def longestOnes(self, arr: List[int], k: int) -> int:
s, e = 0, 0
n = len(arr)
dp = {}
ans = 0
while e < n:
# Add the current element to the frequency dictionary
ele = arr[e]
dp[ele] = dp.get(ele, 0) + 1
# If valid, update answer and expand window
if self.isValid(dp, k):
ans = max(ans, e - s + 1)
e += 1
else:
# Shrink from the left until valid
while s <= e and not self.isValid(dp, k):
left_ele = arr[s]
if dp[left_ele] > 1:
dp[left_ele] -= 1
else:
del dp[left_ele]
s += 1
# After shrinking, update answer if valid
if self.isValid(dp, k):
ans = max(ans, e - s + 1)
e += 1
return ans
What You Will Learn:
- How to apply the sliding window approach to manage a constraint on the number of allowable flips.
- Efficiently tracking the frequency of elements using a dictionary (dp) to decide when to shrink or expand the window.
- Real-world applicability in problems where limited modifications can be made to achieve a continuous segment of favorable elements.
In this chapter, you will learn how to determine the maximum number of fruits that can be collected in two baskets from a row of trees, where each tree has a specific type of fruit. This problem utilizes the sliding window approach and a frequency dictionary to ensure that at most two different fruit types are present in any valid window.
# code
class Solution:
def isValid(self, dp):
return len(dp) <= 2
def totalFruit(self, arr: List[int]) -> int:
s, e = 0, 0
n = len(arr)
dp = {}
ans = 0
while e < n:
# Add the current fruit
fruit_type = arr[e]
dp[fruit_type] = dp.get(fruit_type, 0) + 1
# If valid, update answer
if self.isValid(dp):
ans = max(ans, e - s + 1)
e += 1
else:
# Shrink window until valid
while s <= e and not self.isValid(dp):
left_fruit = arr[s]
if dp[left_fruit] > 1:
dp[left_fruit] -= 1
else:
del dp[left_fruit]
s += 1
# Update answer if valid after shrinking
if self.isValid(dp):
ans = max(ans, e - s + 1)
e += 1
return ans
What You Will Learn:
- How to apply the sliding window approach to keep at most two distinct elements in
a subarray.
- Efficiently managing the current window using a frequency dictionary (dp).
- Techniques for dynamically adjusting the window boundaries in real time, which
generalize to many two-type or k-type problems.
In this chapter, you will learn how to determine the length of the longest substring in which you can replace at most k characters to make all the letters in the substring the same. This problem utilizes a sliding window approach alongside frequency tracking and a maximum frequency counter to decide when a substring is valid.
# code
class Solution:
def isValid(self, k, maxCount, size):
# A window is valid if the number of replacements needed (size - maxCount) is <= k
return (size - maxCount) <= k
def characterReplacement(self, name: str, k: int) -> int:
s, e = 0, 0
n = len(name)
dp = {}
ans = 0
maxCount = 0
while e < n:
# Expand the window by adding the current character
ch = name[e]
dp[ch] = dp.get(ch, 0) + 1
maxCount = max(maxCount, dp[ch])
# Check if the current window is valid
if self.isValid(k, maxCount, e - s + 1):
ans = max(ans, e - s + 1)
e += 1
else:
# Shrink from the left until valid
while s <= e and not self.isValid(k, maxCount, e - s + 1):
left_char = name[s]
dp[left_char] -= 1
if dp[left_char] == 0:
del dp[left_char]
s += 1
if self.isValid(k, maxCount, e - s + 1):
ans = max(ans, e - s + 1)
e += 1
return ans
What You Will Learn:
- How to apply the sliding window strategy to problems involving character
replacement constraints.
- Maintaining a frequency dictionary and a maximum character count to quickly
check validity.
- Balancing window expansion and contraction based on the required replacements
(size−maxCount) staying within k.
In this chapter, we tackle the problem of finding the longest subarray whose sum is exactly k in an array that may contain negative elements. Unlike the strictly non-negative case (which can often be solved with a sliding window), this solution employs prefix sums and a hash map to handle negative, positive, and zero values efficiently.
Key Points:
- Prefix Sum Array:
- Construct an array prefix such that prefix[i] represents the sum of elements from
index 0 to i-1.
- prefix[0] = 0 to simplify calculations.
- Hash Map (dp):
- Stores (prefix_sum -> first_index) pairs, indicating where each prefix sum first
appears.
- Initially contains {0: -1}, meaning a sum of 0 is at index -1.
- Finding the Longest Subarray:
- As you compute prefix[i+1], calculate rem = prefix[i+1] - k.
- If rem is found in the hash map, you can form a subarray of length i - dp[rem]
whose sum is k.
- Update the answer with the maximum length found.
- Time and Space Complexity:
- O(n) time, since you only make one pass through the array.
- O(n) space for the prefix sum array and hash map in the worst case.
# code
class Solution:
def lenOfLongestSubarr(self, arr, k):
n = len(arr)
prefix = [0] * (n + 1)
ans = 0
dp = {0: -1} # prefix sum 0 occurs at index -1
for i in range(n):
prefix[i + 1] = prefix[i] + arr[i]
rem = prefix[i + 1] - k
# If 'rem' already exists in dp, we have a subarray sum = k
if rem in dp:
ans = max(ans, i - dp[rem])
# Store the first occurrence of this prefix sum
if prefix[i + 1] not in dp:
dp[prefix[i + 1]] = i
return ans
What You Will Learn:
- Prefix Sum with Hashing: How to handle arrays containing negative, positive, and
zero elements to achieve an O(n) solution.
- Using a Dictionary to Track Prefix Sums: Efficiently identify subarrays that sum to k
without a nested loop.
- General Application: This approach generalizes to other problems involving
subarray sums, particularly where negative elements are allowed.
In this chapter, you will learn how to find the length of the longest subarray in which the total sum of elements is 0. This is a classic problem solved efficiently with a prefix sum array and a hash map, especially when the array contains both positive and negative numbers.
# code
class Solution:
def maxLen(self, arr):
n = len(arr)
prefix = [0] * (n + 1)
ans = 0
dp = {0: -1} # prefix sum 0 at index -1
k = 0 # target sum = 0
for i in range(n):
prefix[i + 1] = prefix[i] + arr[i]
rem = prefix[i + 1] - k # in this case, rem = prefix[i + 1]
if rem in dp:
ans = max(ans, i - dp[rem])
if prefix[i + 1] not in dp:
dp[prefix[i + 1]] = i
return ans
What You Will Learn:
- How the prefix sum technique can detect subarrays of sum zero without checking
every possible subarray.
- Using a hash map to track previously seen prefix sums for an O(n) solution.
- Strategies to handle both positive and negative numbers in subarray sum problems
effectively.
Are you preparing for Data Structures and Algorithms (DSA) but struggling with Python fundamentals? This course is designed for you!
In Python Fundamentals: Build a Strong Foundation for DSA, you'll learn only the Python concepts that are necessary for DSA. This means no unnecessary theory—just the core Python skills required to solve DSA problems efficiently.
What makes this course unique?
Beginner-Friendly - No prior Python experience needed!
Straight to the Point - Focuses only on what’s required for DSA.
Hands-on Coding - Every concept is explained with real code examples.
Problem-Solving Oriented - Learn Python while solving practical coding problems.
By the end of this course, you'll have the confidence to start learning DSA with Python without worrying about missing Python fundamentals!
What You’ll Learn:
Python Basics (Variables, Data Types, Operators)
Loops and Conditionals (For, While, If-Else)
Functions and Recursion
Lists, Tuples, and Dictionaries (Essential Data Structures)
String Manipulation
Object-Oriented Programming (OOP) Basics
Who This Course Is For:
Beginners in Python who want to focus only on the DSA-related concepts
Students preparing for coding interviews with Python
Anyone taking a DSA course and needs a quick Python refresher
CS/IT students transitioning from another language to Python
Course Requirements:
No prior Python knowledge is needed.
A computer with an internet connection.
Willingness to learn with hands-on coding exercises.