Oops and Ds with real-time
examples.
Topic: Classes and Objects
Definition
Class: A blueprint for creating objects. It defines a set of attributes and
methods that the created objects will have.
Object: An instance of a class. It is created based on the class definition and
can use the attributes and methods defined in the class.
Example in OOP
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display_info(self):
print(f"Product: {self.name}, Price: {self.price}")
# Creating an object of the Product class
product1 = Product("Laptop", 1200)
product1.display_info()
Real-time Example: Amazon
Use Case: Product Management
Class: Product
Attributes: name , price , description , stock_quantity , category
Oops and Ds with real-time examples. 1
Methods: add_to_cart() , display_info() , apply_discount()
In Amazon, each product listed on the site can be represented as an object of the
Product class. The Product class contains attributes such as the product name,
price, description, stock quantity, and category. Methods might include actions
like adding the product to the shopping cart or displaying detailed information
about the product.
Where it is used: When you browse Amazon and see a list of products, each
product is an object instantiated from a product class. The system uses these
objects to display information, manage inventory, and handle user actions such as
adding products to the cart or wish list.
Topic: Inheritance
Definition
Inheritance: A mechanism where a new class (child class) inherits attributes
and methods from an existing class (parent class). This allows for code
reusability and the creation of a hierarchical relationship between classes.
Example
class Electronics(Product):
def __init__(self, name, price, brand):
super().__init__(name, price)
self.brand = brand
def display_info(self):
print(f"Product: {self.name}, Price: {self.price}, Br
and: {self.brand}")
# Creating an object of the Electronics class
electronic1 = Electronics("Smartphone", 700, "Samsung")
electronic1.display_info()
Oops and Ds with real-time examples. 2
Real-time Example: Amazon
Use Case: Category-Specific Product Information
Parent Class: Product
Child Classes: Electronics , Clothing , Books
In Amazon, different types of products (e.g., electronics, clothing, books) share
common attributes like name and price but also have category-specific attributes.
By using inheritance, Amazon can create a base Product class and derive specific
classes like Electronics , Clothing , and Books . Each derived class can have
additional attributes and methods relevant to that category.
Where it is used: When Amazon displays category-specific information and
functionalities, such as technical specifications for electronics or author
information for books, it leverages inheritance to extend the base product
functionality and add specific details.
Topic: Encapsulation
Definition
Encapsulation: Encapsulation is the concept of bundling the data (attributes)
and the methods (functions) that operate on the data into a single unit, called a
class. It restricts direct access to some of the object's components, which is a
means of preventing unintended interference and misuse. Encapsulation is
often achieved through the use of private and public access specifiers.
Example
class Product:
def __init__(self, name, price):
self.__name = name # private attribute
self.__price = price # private attribute
# Getter method for name
def get_name(self):
return self.__name
Oops and Ds with real-time examples. 3
# Setter method for name
def set_name(self, name):
self.__name = name
# Getter method for price
def get_price(self):
return self.__price
# Setter method for price
def set_price(self, price):
if price > 0:
self.__price = price
else:
print("Invalid price!")
# Creating an object of the Product class
product1 = Product("Laptop", 1200)
# Accessing and modifying private attributes through methods
print(product1.get_name())
product1.set_price(1100)
print(product1.get_price())
Real-time Example: Amazon
Use Case: Customer Data Management
Class: Customer
Attributes: __name , __email , __password
Methods: get_name() , set_name() , get_email() , set_email() , set_password()
In Amazon, customer data such as name, email, and password should be
protected from unauthorized access and modification. Using encapsulation,
Amazon can ensure that these details are only accessible and modifiable through
Oops and Ds with real-time examples. 4
well-defined methods, providing a controlled way to access and update customer
information.
Where it is used: When you log in to Amazon and update your profile information,
the system uses encapsulated methods to safely and securely handle your data.
For instance, setting a new password involves validation checks to ensure it meets
security standards before it is updated.
Encapsulation is crucial for maintaining the integrity of data and ensuring that the
internal state of an object is not directly accessible from outside the class. This
concept is widely used in applications like Amazon to manage user data, product
details, and other sensitive information securely.
Topic: Polymorphism
Definition
Polymorphism: Polymorphism is the ability of a function, method, or object to
take on multiple forms. In object-oriented programming, it typically refers to
the ability to use a single interface or method to represent different underlying
forms (data types). This can be achieved through method overloading (same
method name, different parameters) and method overriding (same method
name in different classes with a parent-child relationship).
Example in OOP
Method Overloading (Not directly supported in Python but can be simulated):
class MathOperations:
def add(self, a, b, c=0):
return a + b + c
# Using the method with two arguments
math_ops = MathOperations()
print(math_ops.add(2, 3)) # Output: 5
Oops and Ds with real-time examples. 5
# Using the method with three arguments
print(math_ops.add(2, 3, 4)) # Output: 9
Method Overriding:
class Animal:
def make_sound(self):
print("Animal makes a sound")
class Dog(Animal):
def make_sound(self):
print("Dog barks")
class Cat(Animal):
def make_sound(self):
print("Cat meows")
# Creating objects
animals = [Animal(), Dog(), Cat()]
# Calling the same method on different objects
for animal in animals:
animal.make_sound()
Real-time Example: Amazon
Use Case: Payment Methods
Base Class: PaymentMethod
Derived Classes: CreditCard , PayPal , GiftCard
Amazon allows customers to pay using various methods, such as credit cards,
PayPal, and gift cards. Each payment method has different implementation details
but shares a common interface for processing payments. Polymorphism allows
Oops and Ds with real-time examples. 6
Amazon to process a payment without knowing the specific type of payment
method in advance.
Where it is used: When you select a payment method at checkout, Amazon uses
polymorphism to handle the payment processing. Regardless of whether you
choose a credit card, PayPal, or a gift card, the system calls the process_payment()
method on the chosen payment object, which internally handles the specifics of
that payment method.
Polymorphism allows for flexibility and the ability to extend the system with new
payment methods without modifying existing code that uses the PaymentMethod
interface.
Topic: Abstraction
Definition
Abstraction: Abstraction is the concept of hiding the complex implementation
details and showing only the essential features of the object. It is used to
reduce programming complexity and effort by providing a simplified interface
to interact with complex systems. Abstraction allows focusing on what an
object does instead of how it does it.
Example
from abc import ABC, abstractmethod
class PaymentMethod(ABC):
@abstractmethod
def process_payment(self, amount):
pass
class CreditCard(PaymentMethod):
def process_payment(self, amount):
print(f"Processing credit card payment of ${amount}")
Oops and Ds with real-time examples. 7
class PayPal(PaymentMethod):
def process_payment(self, amount):
print(f"Processing PayPal payment of ${amount}")
class GiftCard(PaymentMethod):
def process_payment(self, amount):
print(f"Processing gift card payment of ${amount}")
# Creating payment method objects
payment_methods = [CreditCard(), PayPal(), GiftCard()]
# Processing payments using abstraction
for method in payment_methods:
method.process_payment(100)
In this example, is an abstract class that defines an abstract method
PaymentMethod
process_payment() . The specific payment method classes ( CreditCard , PayPal ,
GiftCard ) implement this method.
Real-time Example: Amazon
Use Case: Order Processing System
Abstract Class: Order
Concrete Classes: PhysicalProductOrder , DigitalProductOrder , SubscriptionOrder
In Amazon, the order processing system handles different types of orders such as
physical products, digital products, and subscriptions. Each type of order has
specific processing logic. Using abstraction, Amazon can define a general
interface for order processing while allowing specific order types to implement
their unique processing details.
Where it is used: When you place an order on Amazon, the system uses
abstraction to process your order. Regardless of whether you are ordering a
physical book, a digital ebook, or subscribing to a service, the order processing
Oops and Ds with real-time examples. 8
system interacts with a common interface to process the order, while the actual
processing logic is specific to the type of order.
In this example, the Order abstract class defines a process_order() method. The
concrete classes ( PhysicalProductOrder , DigitalProductOrder , SubscriptionOrder )
implement this method with specific details for processing different types of
orders.
Abstraction allows Amazon to manage different order types using a common
interface, simplifying the order processing system while maintaining flexibility and
scalability.
Data Structures
Topic: Stack
Definition
Stack: A stack is a linear data structure that follows the Last In, First Out
(LIFO) principle. This means that the last element added to the stack is the first
one to be removed. It is analogous to a stack of plates, where you can only
add or remove the top plate. Stacks are used in various applications, including
function call management, expression evaluation, and backtracking
algorithms.
Basic Operations
Push: Add an element to the top of the stack.
Pop: Remove and return the top element from the stack.
Peek/Top: Return the top element without removing it.
IsEmpty: Check if the stack is empty.
Example
class Stack:
def __init__(self):
self.items = []
Oops and Ds with real-time examples. 9
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
raise IndexError("Pop from empty stack")
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
raise IndexError("Peek from empty stack")
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Example usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop()) # Output: 3
print(stack.peek()) # Output: 2
print(stack.is_empty()) # Output: False
Real-time Example: Amazon
Use Case: Browsing History Management
Oops and Ds with real-time examples. 10
Scenario: As a user browses through different products on Amazon, their
browsing history is maintained. If the user navigates back, the last visited
product should be shown first.
In Amazon, a stack can be used to manage the browsing history. Each time a user
views a product, it is pushed onto the stack. When the user hits the back button,
the most recently viewed product is popped from the stack and displayed.
Where it is used: When you click on different product links and use the back
button in your browser, Amazon's system uses a stack to keep track of the
browsing history, allowing you to go back to the last viewed product.
In this example, the BrowsingHistory class uses a stack to manage the user's
browsing history. Each product visit is pushed onto the stack, and the back
navigation pops the most recent product from the stack.
Topic: Queue
Definition
Queue: A queue is a linear data structure that follows the First In, First Out
(FIFO) principle. This means that the first element added to the queue will be
the first one to be removed. Queues are commonly used in scenarios where
order of processing is important, such as task scheduling, handling requests in
web servers, and managing print jobs.
Basic Operations
Enqueue: Add an element to the end of the queue.
Dequeue: Remove and return the front element from the queue.
Front: Return the front element without removing it.
IsEmpty: Check if the queue is empty.
Example
class Queue:
def __init__(self):
Oops and Ds with real-time examples. 11
self.items = []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
if not self.is_empty():
return self.items.pop(0)
else:
raise IndexError("Dequeue from empty queue")
def front(self):
if not self.is_empty():
return self.items[0]
else:
raise IndexError("Front from empty queue")
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
# Example usage
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue()) # Output: 1
print(queue.front()) # Output: 2
print(queue.is_empty()) # Output: False
Real-time Example: Amazon
Use Case: Order Processing System
Oops and Ds with real-time examples. 12
Scenario: Amazon needs to process customer orders in the order they are
received. Each order should be handled in a FIFO manner to ensure fairness
and timely processing.
In Amazon, a queue can be used to manage customer orders. Each new order is
enqueued to the end of the queue. The order processing system dequeues the
orders from the front of the queue to process them in the order they were
received.
Where it is used: When you place an order on Amazon, your order enters a queue
for processing. This ensures that orders are handled in the order they are placed,
maintaining a fair and organized system for order fulfillment.
In this example, the OrderQueue class uses a queue to manage customer orders.
Each new order is added to the queue using the place_order() method, and orders
are processed in the order they were placed using the process_order() method.
Topic: Linked List
Definition
Linked List: A linked list is a linear data structure where elements (called
nodes) are linked using pointers. Each node contains two parts: data and a
reference (or pointer) to the next node in the sequence. Unlike arrays, linked
lists do not have a fixed size and can grow or shrink dynamically.
Types of Linked Lists
Singly Linked List: Each node points to the next node in the list.
Doubly Linked List: Each node points to both the next and the previous nodes.
Circular Linked List: The last node points back to the first node, forming a
circle.
Basic Operations
Insertion: Add a new node to the list.
Deletion: Remove a node from the list.
Oops and Ds with real-time examples. 13
Traversal: Access each node sequentially.
Example
Singly Linked List:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def delete(self, data):
current = self.head
if current and current.data == data:
self.head = current.next
current = None
return
prev = None
while current and current.data != data:
prev = current
current = current.next
if current is None:
Oops and Ds with real-time examples. 14
return
prev.next = current.next
current = None
def traverse(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example usage
linked_list = SinglyLinkedList()
linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
linked_list.traverse() # Output: 1 -> 2 -> 3 -> None
linked_list.delete(2)
linked_list.traverse() # Output: 1 -> 3 -> None
Real-time Example: Amazon
Use Case: Wishlist Management
Scenario: Users on Amazon can add items to their wishlist. The items in the
wishlist are managed in a sequence, and users can add or remove items as
they wish.
In Amazon, a linked list can be used to manage a user's wishlist. Each item added
to the wishlist is a node in the linked list. This allows for dynamic addition and
removal of items without needing to shift other items as in an array.
Where it is used: When you add items to your wishlist on Amazon, each item can
be represented as a node in a linked list. This allows Amazon to efficiently manage
the wishlist with dynamic updates as you add or remove items.
In this example, the Wishlist class uses a singly linked list to manage the items in a
user's wishlist. The add_item() method adds a new item to the end of the list, the
Oops and Ds with real-time examples. 15
remove_item() method removes a specified item, and the view_wishlist() method
prints all the items in the wishlist.
Doubly Linked List in Amazon
Use Case: Product Recommendations
Scenario: Amazon recommends products to users based on their browsing
history. A doubly linked list can be used to navigate back and forth between
recommended products, allowing users to see previous and next
recommendations efficiently.
Where it is used: When you browse through recommended products, Amazon can
use a doubly linked list to manage the recommendations, allowing seamless
navigation between them.
Example Implementation:
class ProductNode:
def __init__(self, product_id, details):
self.product_id = product_id
self.details = details
self.next = None
self.prev = None
class ProductRecommendations:
def __init__(self):
self.head = None
def add_product(self, product_id, details):
new_product = ProductNode(product_id, details)
if not self.head:
self.head = new_product
else:
Oops and Ds with real-time examples. 16
current = self.head
while current.next:
current = current.next
current.next = new_product
new_product.prev = current
print(f"Product added: {product_id}")
def view_recommendations_forward(self):
current = self.head
while current:
print(f"Product ID: {current.product_id}, Details: {
current = current.next
def view_recommendations_backward(self):
current = self.head
while current and current.next:
current = current.next
while current:
print(f"Product ID: {current.product_id}, Details: {
current = current.prev
# Example usage
recommendations = ProductRecommendations()
recommendations.add_product("P1001", "Laptop")
recommendations.add_product("P1002", "Smartphone")
recommendations.view_recommendations_forward() # Output: Produc
recommendations.view_recommendations_backward() # Output: Produc
Circular Linked List in Amazon
Use Case: Continuous Carousel of Product Images
Scenario: When viewing a product on Amazon, the product page often
includes a carousel of images that can loop continuously. A circular linked list
can manage these images, allowing seamless cycling through them.
Oops and Ds with real-time examples. 17
Where it is used: When you click through the images of a product, the circular
linked list ensures that you can keep navigating through images without reaching
an end.
Example Implementation:
class ImageNode:
def __init__(self, image_id, url):
self.image_id = image_id
self.url = url
self.next = None
class ImageCarousel:
def __init__(self):
self.head = None
def add_image(self, image_id, url):
new_image = ImageNode(image_id, url)
if not self.head:
self.head = new_image
new_image.next = self.head
else:
current = self.head
while current.next != self.head:
current = current.next
current.next = new_image
new_image.next = self.head
print(f"Image added: {image_id}")
def view_images(self, cycles=1):
if not self.head:
print("No images in carousel")
return
current = self.head
count = 0
while count < cycles:
Oops and Ds with real-time examples. 18
print(f"Image ID: {current.image_id}, URL: {current
current = current.next
if current == self.head:
count += 1
# Example usage
carousel = ImageCarousel()
carousel.add_image("I1001", "image1.jpg")
carousel.add_image("I1002", "image2.jpg")
carousel.add_image("I1003", "image3.jpg")
carousel.view_images(cycles=2) # Output: Images in a loop for s
Topic: Trees
Definition
Tree: A tree is a hierarchical data structure consisting of nodes, with a single
node called the root from which all other nodes branch out. Each node
contains data and references to its child nodes. Trees are used in various
applications, including representing hierarchical data, managing sorted data,
and facilitating fast data retrieval.
Basic Terminology
Root: The topmost node in a tree.
Parent: A node that has one or more child nodes.
Child: A node that is a descendant of another node.
Leaf: A node that does not have any children.
Subtree: A tree consisting of a node and all its descendants.
Height: The length of the longest path from the root to a leaf.
Types of Trees
Binary Tree: A tree where each node has at most two children.
Oops and Ds with real-time examples. 19
Binary Search Tree (BST): A binary tree where the left child of a node
contains only nodes with values less than the parent node, and the right child
contains only nodes with values greater than the parent node.
Balanced Tree: A tree where the height difference between the left and right
subtrees of any node is at most one.
Heap: A special tree-based data structure that satisfies the heap property
(min-heap or max-heap).
Examples and Real-time Use Cases in Amazon
Binary Tree
Use Case: Organizational Hierarchy
Scenario: Amazon has a hierarchical organizational structure where each
manager can have multiple subordinates. This structure can be represented as
a binary tree, where each node represents an employee, with edges
representing reporting relationships.
Binary Search Tree (BST)
Use Case: Product Inventory Management
Scenario: Amazon manages a vast inventory of products. A BST can be used
to store and retrieve product information efficiently based on product IDs.
Heap
Use Case: Priority Queue for Order Processing
Scenario: Amazon processes orders based on priority. A min-heap can be
used to manage and retrieve the highest-priority orders efficiently.
Topic: Graphs
Definition
Graph: A graph is a non-linear data structure consisting of a set of vertices
(nodes) and a set of edges connecting these vertices. Graphs are used to
Oops and Ds with real-time examples. 20
represent relationships between different entities and are widely used in
various applications such as social networks, maps, and network routing
algorithms.
Basic Concepts
Vertex (Node): Represents an entity in the graph.
Edge: Represents a connection between two vertices.
Directed Graph: A graph where edges have a direction.
Undirected Graph: A graph where edges have no direction.
Weighted Graph: A graph where edges have weights or costs associated with
them.
Types of Graphs
Directed Graph (Digraph): A graph where edges have a direction.
Undirected Graph: A graph where edges have no direction.
Weighted Graph: A graph where edges have weights or costs associated with
them.
Cyclic Graph: A graph that contains at least one cycle.
Acyclic Graph: A graph that does not contain any cycles.
Example and Real-time Use Cases in Amazon
Directed Graph
Use Case: Delivery Route Optimization
Scenario: Amazon operates a vast network of delivery routes between
warehouses, distribution centers, and customer locations. A directed graph
can represent these routes, with vertices representing locations and directed
edges representing the direction of travel between locations.
Undirected Graph
Use Case: Product Recommendations
Oops and Ds with real-time examples. 21
Scenario: Amazon provides personalized product recommendations to users
based on their browsing and purchasing history. An undirected graph can
represent the relationships between products, with edges indicating related or
frequently co-purchased products.
Weighted Graph
Use Case: Shortest Path Finding
Scenario: Amazon's logistics system needs to find the shortest route between
warehouses to optimize delivery times. A weighted graph can represent the
distances between locations, with edge weights indicating travel distances.
Examples of Oops in Daily used applications.
Inheritance in Daily Use Applications
1. WhatsApp
Real-time Example: Message handling and display.
Explanation: In WhatsApp, message handling and display functionality can
be implemented using inheritance. For example, the base class for
message display might define common features like sender name,
message content, and timestamp, while subclasses can inherit from this
base class to implement specific message types like text, image, or video
messages.
2. Instagram
Real-time Example: User profile customization.
Explanation: In Instagram, user profile customization features like adding
bio, profile picture, and links can be implemented using inheritance. The
base class for user profiles might include common attributes like
username and follower count, while subclasses can inherit from this base
class to implement additional features for business profiles, verified
accounts, etc.
Oops and Ds with real-time examples. 22
3. YouTube
Real-time Example: Video content categorization.
Explanation: In YouTube, video content categorization features like
genres, tags, and recommended videos can be implemented using
inheritance. The base class for videos might include common attributes
like title, duration, and upload date, while subclasses can inherit from this
base class to categorize videos into genres like music, gaming, or
education.
4. Amazon
Real-time Example: Product recommendation algorithms.
Explanation: In Amazon, product recommendation algorithms can be
implemented using inheritance. The base class for product
recommendations might include common attributes like product name,
price, and average rating, while subclasses can inherit from this base
class to implement recommendation strategies based on user preferences,
purchase history, or trending products.
5. Netflix
Real-time Example: Content streaming and playback.
Explanation: In Netflix, content streaming and playback functionality can
be implemented using inheritance. The base class for media content might
include common attributes like title, duration, and genre, while subclasses
can inherit from this base class to implement specific playback features
for different types of content like movies, TV shows, or documentaries.
Polymorphism in Daily Use Applications
1. WhatsApp
Real-time Example: Message sending functionality.
Explanation: In WhatsApp, polymorphism can be seen in the message
sending functionality. Regardless of the type of message (text, image,
video), users interact with the same interface (e.g., typing in a message
Oops and Ds with real-time examples. 23
box and pressing send), but the behavior of the system changes based on
the type of message being sent.
2. Instagram
Real-time Example: Content sharing options.
Explanation: In Instagram, polymorphism can be observed in content
sharing options. Users can share various types of content (e.g., posts,
stories, IGTV videos), and the sharing interface adapts dynamically based
on the type of content being shared, allowing users to share content
seamlessly.
3. YouTube
Real-time Example: Video playback controls.
Explanation: In YouTube, polymorphism can be seen in video playback
controls. Regardless of the type of video content (e.g., music videos,
tutorials, vlogs), users interact with the same playback controls (e.g., play,
pause, seek), but the behavior of these controls varies based on the type
of video being played.
4. Amazon
Real-time Example: Payment processing methods.
Explanation: In Amazon, polymorphism can be observed in payment
processing methods. Users can choose from various payment options
(e.g., credit/debit card, net banking, UPI), and the payment processing
system adapts dynamically to handle different payment methods while
providing a consistent user experience.
5. Netflix
Real-time Example: Content recommendation algorithms.
Explanation: In Netflix, polymorphism can be seen in content
recommendation algorithms. The recommendation system dynamically
adapts to user preferences and viewing history, providing personalized
recommendations for different users while maintaining a consistent
interface for browsing and discovering content.
Oops and Ds with real-time examples. 24
Abstraction in Daily Use Applications
1. WhatsApp
Real-time Example: User interface design.
Explanation: In WhatsApp, abstraction can be observed in the user
interface design. Users interact with simplified and intuitive interfaces that
hide complex underlying processes, such as message encryption and
network communication, allowing users to focus on communication
without being overwhelmed by technical details.
2. Instagram
Real-time Example: Image editing features.
Explanation: In Instagram, abstraction is evident in image editing features.
Users can apply various filters, effects, and enhancements to their photos
with simple taps and gestures, abstracting away the complexity of image
processing algorithms and allowing users to create visually appealing
content effortlessly.
3. YouTube
Real-time Example: Video recommendation algorithms.
Explanation: In YouTube, abstraction can be seen in video
recommendation algorithms. Behind the scenes, sophisticated machine
learning algorithms analyze user behavior and content metadata to
generate personalized recommendations, presenting users with relevant
videos without exposing the intricacies of the recommendation process.
4. Amazon
Real-time Example: Search and filtering functionality.
Explanation: In Amazon, abstraction is evident in search and filtering
functionality. Users can search for products and apply filters based on
various criteria such as price, brand, and customer ratings, abstracting
away the complexity of database queries and allowing users to find
products efficiently.
Oops and Ds with real-time examples. 25
5. Netflix
Real-time Example: Content streaming and caching.
Explanation: In Netflix, abstraction can be observed in content streaming
and caching mechanisms. Users can seamlessly stream high-quality video
content on various devices, abstracting away the complexities of video
encoding, adaptive bitrate streaming, and content caching, ensuring a
smooth viewing experience regardless of network conditions.
Encapsulation in Daily Use Applications
1. WhatsApp
Real-time Example: Message encryption and decryption.
Explanation: In WhatsApp, message encryption and decryption are
encapsulated within the messaging system. Users send and receive
messages without needing to know the details of encryption algorithms or
key management, ensuring secure communication while hiding the
complexities of cryptography.
2. Instagram
Real-time Example: User authentication and authorization.
Explanation: In Instagram, user authentication and authorization
processes are encapsulated within the login system. Users log in with their
credentials, and the system verifies their identity and permissions without
exposing the internal mechanisms used for user management and access
control.
3. YouTube
Real-time Example: Video upload and processing.
Explanation: In YouTube, video upload and processing are encapsulated
within the content management system. Content creators upload videos
through a user-friendly interface, and behind the scenes, the system
handles video processing tasks such as transcoding, thumbnail
generation, and content moderation without user intervention.
Oops and Ds with real-time examples. 26
4. Amazon
Real-time Example: Order processing and fulfillment.
Explanation: In Amazon, order processing and fulfillment operations are
encapsulated within the e-commerce platform. Users place orders, and
the system orchestrates various processes such as inventory
management, payment processing, and shipping logistics transparently,
ensuring timely delivery of products without exposing internal workflows.
5. Netflix
Real-time Example: Content recommendation algorithms.
Explanation: In Netflix, content recommendation algorithms are
encapsulated within the recommendation engine. Users receive
personalized recommendations based on their viewing history and
preferences, and the system continuously refines recommendations
without revealing the underlying algorithms or data processing techniques.
Examples of Data structures in Daily used applications.
Stack and Queue in Daily Use Applications
1. WhatsApp
Stack Example: Message Undo Feature.
Explanation: When typing a message, users can undo their last action
by popping the last character or word from a stack. This feature allows
users to quickly correct typing mistakes without deleting the entire
message.
Queue Example: Message Sending Queue.
Explanation: Outgoing messages are placed in a queue before being
sent to the recipient. This ensures that messages are sent in the order
they were composed, maintaining the chronological flow of
conversations.
2. Instagram
Oops and Ds with real-time examples. 27
Stack Example: Filters Applied to Photos.
Explanation: When applying filters to photos, Instagram uses a stack
to track the sequence of filter effects applied by the user. Users can
undo or redo filter changes by popping or pushing filters onto the
stack.
Queue Example: Upload Queue for Stories.
Explanation: When uploading multiple stories, Instagram uses a queue
to manage the order of uploads. Stories are queued up and processed
sequentially, ensuring that they are uploaded in the order they were
selected.
3. YouTube
Stack Example: Video Playback History.
Explanation: YouTube maintains a stack of recently watched videos in
the user's playback history. Users can navigate back through their
watch history by popping videos off the stack, allowing them to revisit
previously viewed content.
Queue Example: Video Playlist.
Explanation: When creating a playlist, YouTube uses a queue to
maintain the order of videos. Users can add videos to the end of the
playlist queue and remove videos from the front, controlling the
playback sequence.
4. Amazon
Stack Example: Browsing History.
Explanation: Amazon tracks users' browsing history using a stack data
structure. Each product page visited is pushed onto the stack, allowing
users to navigate back through previously viewed products.
Queue Example: Order Fulfillment Queue.
Explanation: When processing orders, Amazon uses a queue to
manage the order fulfillment process. Orders are queued up for
Oops and Ds with real-time examples. 28
processing, and items are picked and packed in the order they were
received, ensuring fairness and efficiency.
5. Netflix
Stack Example: Recently Watched List.
Explanation: Netflix maintains a stack of recently watched titles in the
user's profile. Users can navigate back through their viewing history
by popping titles off the stack, making it easy to resume watching
where they left off.
Queue Example: Content Recommendation Queue.
Explanation: Netflix uses a queue to manage the delivery of content
recommendations to users. Recommendations are queued up based
on user preferences and viewing history, ensuring that users receive
personalized recommendations in a timely manner.
Linked Lists in Daily Use Applications
1. WhatsApp
Singly Linked List Example: Chat Message History.
Explanation: WhatsApp stores chat message history in a singly linked
list. Each message node contains message content, sender
information, and a pointer to the next message in the conversation,
allowing users to navigate through their chat history.
Doubly Linked List Example: Forward and Backward Navigation.
Explanation: WhatsApp uses a doubly linked list to implement forward
and backward navigation within chat conversations. Each message
node has pointers to both the previous and next messages, enabling
users to navigate seamlessly through their chat history.
2. Instagram
Singly Linked List Example: Story Viewing Order.
Oops and Ds with real-time examples. 29
Explanation: Instagram's story feature maintains the order of story
posts in a singly linked list. Each story node contains user-generated
content and a pointer to the next story, allowing users to view stories
in sequential order.
Doubly Linked List Example: Followers and Following Lists.
Explanation: Instagram's followers and following lists are implemented
using doubly linked lists. Each user node contains profile information
and pointers to the previous and next users in the list, facilitating
bidirectional navigation through follower and following lists.
3. YouTube
Singly Linked List Example: Video Recommendations.
Explanation: YouTube's recommendation system stores recommended
videos in a singly linked list. Each video node contains metadata and a
pointer to the next recommended video, allowing users to scroll
through recommended content.
Circular Linked List Example: Autoplay Queue.
Explanation: YouTube's autoplay feature uses a circular linked list to
create a loop of suggested videos. The last video in the autoplay
queue points back to the first video, creating a continuous playback
experience for users.
4. Amazon
Singly Linked List Example: Shopping Cart Items.
Explanation: Amazon's shopping cart stores items in a singly linked
list. Each item node contains product details and a pointer to the next
item in the cart, enabling users to add, remove, and navigate through
their shopping cart contents.
Doubly Linked List Example: Order History.
Explanation: Amazon's order history is implemented using a doubly
linked list. Each order node contains order details and pointers to the
previous and next orders, allowing users to track their purchase history
and navigate through past orders.
Oops and Ds with real-time examples. 30
5. Netflix
Singly Linked List Example: Watchlist.
Explanation: Netflix's watchlist stores titles in a singly linked list. Each
title node contains metadata and a pointer to the next title in the
watchlist, enabling users to add, remove, and navigate through their
list of saved titles.
Circular Linked List Example: Continue Watching Queue.
Explanation: Netflix's "continue watching" queue uses a circular linked
list to manage the playback order of partially watched titles. The last
watched title points back to the first title, allowing users to seamlessly
resume playback from where they left off.
Trees in Daily Use Applications
1. WhatsApp
Binary Tree Example: Contact List.
Explanation: WhatsApp's contact list can be organized as a binary tree
where each node represents a contact. The tree structure allows for
efficient searching and sorting of contacts based on names or phone
numbers.
Binary Search Tree (BST) Example: Chat Search.
Explanation: WhatsApp can use a binary search tree to implement
chat search functionality. Messages are stored in a BST based on
timestamps, allowing for quick retrieval of messages within a specific
time range.
2. Instagram
Binary Tree Example: Followers and Following Graph.
Explanation: Instagram's followers and following relationships can be
represented as a binary tree structure. Each user node has child nodes
Oops and Ds with real-time examples. 31
representing followers or users being followed, facilitating efficient
management of social connections.
Balanced Tree (AVL Tree) Example: User Search.
Explanation: Instagram can use a balanced tree like an AVL tree to
implement user search functionality. User profiles are stored in a
balanced tree based on usernames, ensuring fast search operations
with minimal tree height.
3. YouTube
Binary Tree Example: Video Categories.
Explanation: YouTube's video categories can be organized as a binary
tree structure. Each node represents a category, and child nodes
represent subcategories, enabling users to navigate through videos
efficiently.
Heap Example: Trending Videos.
Explanation: YouTube's trending videos can be managed using a heap
data structure. Videos are prioritized based on views or engagement
metrics, allowing the platform to display the most popular content to
users in real-time.
4. Amazon
Binary Tree Example: Product Categories.
Explanation: Amazon's product categories can be structured as a
binary tree. Each node represents a category, and child nodes
represent subcategories, providing a hierarchical organization of
products for users to browse.
Trie Example: Auto-suggestion in Search.
Explanation: Amazon's search feature can utilize a trie data structure
for auto-suggestion. The trie stores prefixes of product names,
allowing the system to quickly suggest relevant search queries as
users type.
5. Netflix
Oops and Ds with real-time examples. 32
Binary Tree Example: Genre Classification.
Explanation: Netflix's movie and TV show genres can be classified
using a binary tree structure. Each node represents a genre, and child
nodes represent subgenres, facilitating the categorization and
recommendation of content.
B-Tree Example: Content Indexing.
Explanation: Netflix can use a B-tree data structure to index its vast
library of content. B-trees provide efficient storage and retrieval of
content metadata, ensuring fast access to titles for browsing and
streaming.
Graphs in Daily Use Applications
1. WhatsApp
Directed Graph Example: Message Delivery Network.
Explanation: WhatsApp's message delivery network can be
represented as a directed graph, where each user is a node and
messages are directed edges. This graph structure facilitates the
routing and delivery of messages between users.
Undirected Graph Example: Contact Network.
Explanation: WhatsApp's contact network can be represented as an
undirected graph, where each user is a node and mutual contacts are
undirected edges. This graph structure enables the visualization of
social connections between users.
2. Instagram
Directed Graph Example: Follower/Following Network.
Explanation: Instagram's follower/following relationships form a
directed graph, where each user is a node and following relationships
are directed edges. This graph structure enables users to visualize
their social connections and activity.
Oops and Ds with real-time examples. 33
Weighted Graph Example: Engagement Network.
Explanation: Instagram's engagement network can be represented as
a weighted graph, where each user is a node and engagement metrics
(likes, comments) between users are weighted edges. This graph
structure helps identify influential users and popular content.
3. YouTube
Directed Graph Example: Video Recommendation Network.
Explanation: YouTube's video recommendation system operates on a
directed graph, where each video is a node and recommended videos
are directed edges. This graph structure enables personalized video
recommendations based on user preferences and viewing history.
Cyclic Graph Example: Watch History.
Explanation: YouTube's watch history can be represented as a cyclic
graph, where each video is a node and watched-next relationships
form cycles. This graph structure enables users to navigate through
their viewing history and revisit previously watched content.
4. Amazon
Directed Graph Example: Product Recommendation Network.
Explanation: Amazon's product recommendation system operates on
a directed graph, where each product is a node and recommended
products are directed edges. This graph structure facilitates
personalized product recommendations based on user browsing and
purchasing history.
Acyclic Graph Example: Order Fulfillment Network.
Explanation: Amazon's order fulfillment process can be represented
as an acyclic graph, where each order is a node and dependencies
between orders form a directed acyclic graph (DAG). This graph
structure helps optimize the order processing workflow and ensure
timely delivery.
5. Netflix
Oops and Ds with real-time examples. 34
Directed Graph Example: Content Recommendation Network.
Explanation: Netflix's content recommendation system operates on a
directed graph, where each title is a node and recommended titles are
directed edges. This graph structure enables personalized content
recommendations based on user preferences and viewing behavior.
Weighted Graph Example: Content Similarity Network.
Explanation: Netflix's content similarity network can be represented as
a weighted graph, where each title is a node and similarity scores
between titles are weighted edges. This graph structure helps identify
related content and improve content discovery for users.
Oops and Ds with real-time examples. 35