Data+Structures+and+Algorithms

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Data Structures and Algorithms

Data structure refers to the process whereby the data can be stored and organized in a way that the user can access and utilize the data efficiently.
Various algorithms are present to work with the data structures. Therefore, the data structure includes a group of data values, their relation to other
elements, and also the operations that can be carried over the data values.

Programs=algorithms+data structures
Data structures=related data+allowed operations on that data

Common Interview Questions Important Topics:


1. What are Data Structures? 1. Types of Data Structures
2. What are some applications of Data structures? • Linear Data Structures
3. Describe the types of Data Structures? • Non-Linear Data Structures

4. What is a stack data structure? What are the applications 2. Object Oriented Programming
of stack? • Class and Objects
5. What are different operations available in stack data • Methods
structure?
3. Stacks
6. What is a queue data structure? What are the applications
• Stacks Operations
of queue?
• Methods
7. What are different operations available in queue data
4. Queue
structure?
• Queue Operations
8. Differentiate between stack and queue data structure.
• Python Implementation
Types of Data Structures

Data structures are broadly classified into primitive and non-primitive types. Primitive data types are the building blocks of non-primitive data structures.
Examples of primitive data types are integer, float, and string. Collection of primitive data structures form non-primitive data structures like lists, tuples, sets
etc.
Non-primitive data structures are again broadly classified into two types based on how they store the data:

1. Linear data structures


• The storage of data takes place sequentially or in a linear fashion. Here, every element stored in the structure is linked to its neighbouring elements.
The elements can be accessed in a single run as they are arranged linearly.
• Being linearly stored in the memory, implementation is an easy process since the computer’s memory is also linear. You will understand this better in the
next segment on RAM vs Storage.
• Example: Lists, stacks, queues and linked lists

2. Non-Linear data structures


• As the name suggests, non-linear data structures are arranged in a non-contiguous manner in the memory. The elements don’t have a set path to connect to
the other elements but have multiple paths. Traversing through the elements is not possible in one run as the data is non-linearly arranged.
• An element in a non-linear data structure may be connected with multiple elements, unlike linear data structure where the elements are connected only to
both of its neighbouring elements, This makes the implementation of a non-linear data structure slightly more challenging than a linear data structure.
However, if done correctly, it can lead to the effective usage of memory.
• Example: Graphs and Trees

Linear data structures like stacks, queues, deques and linked lists are user-defined data structures. The term user-defined means that the user is allowed to
define those data structures on their own which we will be learning in the subsequent sessions. In this course, we will be focusing only on linear data
structures.
Data Structures

Primitive Data Structures Non-Primitive Data Structures

Integer Real Character Boolean Linear Data Structures Non-linear Data Structures

Arrays Trees
Linked List Graphs
Stacks

Queues

RAM Vs Storage:
• RAM is a temporary memory space whereas storage is permanent memory space.
• All data storage and processing during computation occupies memory, that is RAM as it is designed to provide fast run-time access to the data.
Hence, it is crucial to choose the right data structure for efficient computation.
• RAM is available in GBs as opposed to storage that is available in TBs.
Object Oriented Programming:
Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and
maintenance by providing some concepts: Object. Class. Inheritance.
1. Class:
A class is a collection of objects. A class contains the blueprints or the prototype from which the objects are being created. It is a logical entity that contains
some attributes and methods.
• Classes are created by keyword class.
• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute
2. Objects:
The object is an entity that has a state and behavior associated with it.
An object consists of :
• State: It is represented by the attributes of an object. It also reflects the properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the response of an object to other objects.
• Identity: It gives a unique name to an object and enables one object to interact with other objects.
class Dog: class Dog:

# class attribute # class attribute


attrl = "mammal" attrl = "mammal"

# Instance attribute # Instance attribute


def __init__(self, name): def __init__(self, name):
self.name = name self.name = name

# Driver code def speak (self):


# Object instantiation print ("My name is {}".format (self.name))
Rodger = Dog ("Rodger")
Tommy = Dog ("Tommy") # Driver code
# Object instantiation
# Accessing class attributes Rodger = Dog ("Rodger")
print ("Rodger is a {}".format (Rodger.__class_____.attr1)) Tommy = Dog ("Tommy")
print("Tommy is also a {}".format (Tommy.. class.attr1)) -
# Accessing class methods
# Accessing instance attributes Rodger.speak ()
print ("My name is {}".format (Rodger.name)) Tommy.speak ()
print("My name is {}".format (Tommy.name))

Method vs Functions:
1. Python functions are called generically, methods are called on an object since we call a method on an object, it can access the data within it.
2. A 'Method' may alter an object’s state, but Python 'Function' usually only operates on it, and then returns a valu

● Inheritance: Inheritance is the capability of one class to derive or inherit the properties from another class. The class that derives properties is called
the derived class or child class and the class from which the properties are being derived is called the base class or parent class.

● Polymorphism: Polymorphism simply means having many forms. For example, we need to determine if the given species of birds fly or not, using
polymorphism we can do this using a single function.

● Encapsulation: It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables
and methods directly and can prevent the accidental modification of data.

● Data Abstraction: It hides the unnecessary code details from the user. Also, when we do not want to give out sensitive parts of our code
implementation and this is where data abstraction came.
Stacks: Stacks are data structures that follow Last In First Out order The element that enters the stack, at last, will be removed first. A stack of books is
an example of how a stack works. Then you saw how browser history or an undo button makes use of the stack data structure.

Stacks Operations:

● push(object element): It inserts an element to the top of a stack.


● pop(): It removes an element from the top of a stack.
● isEmpty(): It returns true if a stack is empty; otherwise false.
open_list = ["[", "{",""]
● peek(): It returns the element at the top of a stack but will not remove close_list = ["]", "}", ")"]
it from the stack.
#Function to check parentheses
● size(): It returns the size of the stack.
def check (myStr):
stack = []
Stacks Based Algorithm for Balanced Parenthesis Problem: for i in myStr:
● Parse through the given string character by character if i in open_list:
stack.append(i)
● Every time you encounter an opening parenthesis "("push it into elif i in close_list:
the stack and every time you encounter a ")' pop it out of the stack. pos = close_list.index (i)
if ((len(stack) > 0) and
● There are two correctness conditions to be checked
(open_list [pos] == stack [len (stack)-1])) :
The stack should be empty at the end of the scan stack.pop()
else:
● If the stack is not empty at the end of the scan, it means return "Unbalanced"
that there are more opening parentheses than closing if len(stack) == 0:
parentheses. return "Balanced"
Pop() cannot be called on an empty stack. Example: 0)0 else:
return "Unbalanced"
● Popping from an empty stack at any point of parsing
means that there are closing parentheses than opening # Driver code
string = "{[]{()}}"
parentheses. Parsing can be stopped as soon this
print (string, "-", check (string))
condition is encountered to return the given parentheses
is not balanced. string = "[{}{})(}"
print (string, "-", check (string))

string = "((O)"
print (string, "-", check (string))
Queues: Queues are data structures that follow First In First Out order The element that enters the queue first, will be removed first from the queue.
A ticket counter or a playlist of songs is an example of how a queue works. Then you saw how a shared office printer makes use of a queue data structure.

Queue Operations:
from pythonds. basic import Queue
● Enqueue(object element): It inserts an element to the rear of the queue.
● Dequeue(): It removes an element from the front of a queue. def hotPotato (namelist, num):
simqueue Queue() =
● isEmpty(): It returns true if a queue is empty; otherwise false. for name in namelist:
simqueue.enqueue (name)
● size(): It returns the size of the queue.
● peek(): It returns the element at the front of a queue but will while simqueue.size() > 1:
not remove it from queue. for i in range (num):
simqueue.enqueue (simqueue.dequeue())
Note:
In the user-defined class of 'Queue', you used the convention of the left simqueue.dequeue()
end as rear and the right end as the front. You learned that swapping the
front and rear ends of the queue will not change the FIFO property of the return simqueue.dequeue()
queue as long as insertion happens from the rear end and the removal
happens at the front end of any convention used.

Queue Based Algorithm for Hot Potato Problem:


• Store the given list of players in a queue. Since the first person in the given list of players starts the game, keep the first player at the front of the
queue, the second player in the input list will be behind the first player. The order of the player is in the original list is retained in the queue.
• The number of passes, after which a player is eliminated is taken as an input. For simplicity, we'll assume that this number is constant.
• Keep the position of the ball fixed in the front end of the queue. Since we have the position of the ball fixed, we will move the players instead of
passing the ball.
• The player at the front end of the queue will always be having the ball. Perform the necessary enqueue and dequeue operations based on the
number of passes until only one person remains in the queue.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy