Data Structure And Application (1333203) - Summer 2024 Solution

Solution guide for Data Structure And Application (1333203) Summer 2024 exam

Question 1(a) [3 marks]

Define linear data structure and give its examples.

Answer: A linear data structure is a collection of elements arranged in sequential order where each element has exactly one predecessor and one successor (except first and last elements).

Table: Linear Data Structures Examples

Data StructureDescription
ArrayFixed-size collection of elements accessed by index
Linked ListChain of nodes with data and reference to next node
StackLIFO (Last In First Out) structure
QueueFIFO (First In First Out) structure

Mnemonic: "ALSQ are in a Line"

Question 1(b) [4 marks]

Define time and space complexity.

Answer: Time and space complexity measure algorithm efficiency in terms of execution time and memory usage as input size grows.

Table: Complexity Comparison

Complexity TypeDefinitionMeasurementImportance
Time ComplexityMeasures execution time required by an algorithm as a function of input sizeBig O notation (O(n), O(1), O(n²))Determines how fast an algorithm runs
Space ComplexityMeasures memory space required by an algorithm as a function of input sizeBig O notation (O(n), O(1), O(n²))Determines how much memory an algorithm needs

Mnemonic: "TS: Time-Speed and Space-Storage"

Question 1(c) [7 marks]

Explain the concept of class and object with example.

Answer: Classes and objects are fundamental OOP concepts where classes are blueprints for creating objects with attributes and behaviors.

Diagram: Class and Object Relationship

Code Example:

Python
  • Class: Blueprint defining attributes (name, rollNo, marks) and methods (displayInfo)
  • Object: Instance (student1) created from the class with specific values

Mnemonic: "CAR - Class defines Attributes and Routines"

Question 1(c) OR [7 marks]

Explain instance method, class method and static method with example.

Answer: Python supports three method types: instance, class, and static methods, each serving different purposes.

Table: Comparison of Method Types

Method TypeDecoratorFirst ParameterPurposeAccess
Instance MethodNoneselfOperate on instance dataCan access/modify instance state
Class Method@classmethodclsOperate on class dataCan access/modify class state
Static Method@staticmethodNoneUtility functionsCannot access instance or class state

Code Example:

Python

Mnemonic: "ICS: Instance-Self, Class-Cls, Static-Solo"

Question 2(a) [3 marks]

Explain concept of recursive function.

Answer: A recursive function is a function that calls itself during its execution to solve smaller instances of the same problem.

Diagram: Recursive Function Execution

Mnemonic: "BASE and RECURSE - Base case stops, Recursion repeats"

Question 2(b) [4 marks]

Define stack and queue.

Answer: Stack and queue are linear data structures with different access patterns for data insertion and removal.

Table: Stack vs Queue

FeatureStackQueue
Access PatternLIFO (Last In First Out)FIFO (First In First Out)
OperationsPush (insert), Pop (remove)Enqueue (insert), Dequeue (remove)
Access PointsSingle end (top)Two ends (front, rear)
VisualizationLike plates stacked verticallyLike people in a line
ApplicationsFunction calls, undo operationsPrint jobs, process scheduling

Mnemonic: "SLIFF vs QFIFF - Stack-LIFO vs Queue-FIFO"

Question 2(c) [7 marks]

Explain basic operations on stack.

Answer: Stack operations follow LIFO (Last In First Out) principle with the following basic operations:

Table: Stack Operations

OperationDescriptionTime Complexity
PushInsert element at the topO(1)
PopRemove element from the topO(1)
Peek/TopView top element without removingO(1)
isEmptyCheck if stack is emptyO(1)
isFullCheck if stack is full (for array implementation)O(1)

Diagram: Stack Operations

goat

Code Example:

Python

Mnemonic: "PIPES - Push In, Pop Exit, See top"

Question 2(a) OR [3 marks]

Define singly linked list.

Answer: A singly linked list is a linear data structure with a collection of nodes where each node contains data and a reference to the next node.

Diagram: Singly Linked List

goat

Mnemonic: "DNL - Data and Next Link"

Question 2(b) OR [4 marks]

Explain Enqueue and Dequeue operations on Queue.

Answer: Enqueue and Dequeue are the primary operations for adding and removing elements in a queue data structure.

Table: Queue Operations

OperationDescriptionImplementationTime Complexity
EnqueueAdd element at the rear endqueue.append(element)O(1)
DequeueRemove element from the front endelement = queue.pop(0)O(1) with linked list, O(n) with array

Diagram: Queue Operations

goat

Mnemonic: "ERfDFr - Enqueue at Rear, Dequeue from Front"

Question 2(c) OR [7 marks]

Convert expression A+B/C+D to postfix and evaluate postfix expression using stack assuming some values for A, B, C and D.

Answer: Converting and evaluating the expression "A+B/C+D" using stack:

Step 1: Convert to Postfix

Table: Infix to Postfix Conversion

SymbolStackOutputAction
AAAdd to output
++APush to stack
B+A BAdd to output
/+ /A BPush to stack (higher precedence)
C+ /A B CAdd to output
++A B C /Pop all higher/equal precedence, push +
D+A B C / + DAdd to output
EndA B C / + D +Pop remaining operators

Final Postfix: A B C / + D +

Step 2: Evaluate with values A=5, B=10, C=2, D=3

Table: Postfix Evaluation

SymbolStackCalculation
5 (A)5Push value
10 (B)5, 10Push value
2 (C)5, 10, 2Push value
/5, 510/2 = 5
+105+5 = 10
3 (D)10, 3Push value
+1310+3 = 13

Result: 13

Mnemonic: "PC-SE - Push operands, Calculate when operators, Stack holds Everything"

Question 3(a) [3 marks]

Enlist applications of Linked List.

Answer: Linked lists are versatile data structures with many practical applications.

Table: Applications of Linked List

ApplicationWhy Linked List is Used
Dynamic Memory AllocationEfficient insertion/deletion without reallocation
Implementing Stacks & QueuesCan grow and shrink as needed
Undo FunctionalityEasy to add/remove operations from history
Hash TablesFor handling collisions via chaining
Music PlaylistsEasy navigation between songs (next/previous)

Mnemonic: "DSUHM - Dynamic allocation, Stacks & queues, Undo, Hash tables, Music players"

Question 3(b) [4 marks]

Explain creation of singly linked list in python.

Answer: Creating a singly linked list in Python involves defining a Node class and implementing basic operations.

Code Example:

Python

Diagram: Creating a Linked List

Mnemonic: "CHEN - Create nodes, Head first, End attachment, Next pointers"

Question 3(c) [7 marks]

Write a code to insert a new node at the beginning and end of singly linked list.

Answer: Adding nodes at the beginning and end of a singly linked list requires different approaches.

Code Example:

Python

Diagram: Insertion Operations

goat

Mnemonic: "BEN - Beginning is Easy and Next-based, End Needs traversal"

Question 3(a) OR [3 marks]

Write a code to count the number of nodes in singly linked list.

Answer: Counting nodes requires traversing the entire linked list from head to tail.

Code Example:

Python

Diagram: Counting Nodes

Mnemonic: "CIT - Count Incrementally while Traversing"

Question 3(b) OR [4 marks]

Match appropriate options from column A and B

Answer: The matching between different linked list types and their characteristics:

Table: Matching Linked List Types with Characteristics

Column AColumn BMatch
1. Singly Linked Listc. Nodes contain data and a reference to the next node1-c
2. Doubly Linked Listd. Nodes contain data and references to both the next and previous nodes2-d
3. Circular Linked Listb. Nodes form a loop where the last node points to the first node3-b
4. Node in a Linked Lista. Basic unit containing data and references4-a

Diagram: Different Linked List Types

goat

Mnemonic: "SDCN - Single-Direction, Double-Direction, Circular-Connection, Node-Component"

Question 3(c) OR [7 marks]

Explain deletion of first and last node in singly linked list.

Answer: Deleting nodes from a singly linked list varies in complexity based on the position (first vs. last).

Table: Deletion Comparison

PositionApproachTime ComplexitySpecial Case
First NodeChange head pointerO(1)Check if list is empty
Last NodeTraverse to second-last nodeO(n)Handle single node list

Code Example:

Python

Diagram: Deletion Operations

goat

Mnemonic: "FELO - First is Easy, Last needs One-before-last"

Question 4(a) [3 marks]

Explain concept of doubly linked list.

Answer: A doubly linked list is a bidirectional linear data structure with nodes containing data, previous, and next references.

Diagram: Doubly Linked List

goat

Mnemonic: "PDN - Previous, Data, Next"

Question 4(b) [4 marks]

Explain concept of linear search.

Answer: Linear search is a simple sequential search algorithm that checks each element one by one until finding the target.

Table: Linear Search Characteristics

AspectDescription
WorkingSequentially check each element from start to end
Time ComplexityO(n) - worst and average case
Best CaseO(1) - element found at first position
SuitabilitySmall lists or unsorted data
AdvantageSimple implementation, works on any collection

Diagram: Linear Search Process

Mnemonic: "SCENT - Search Consecutively Each element until Target"

Question 4(c) [7 marks]

Write a code to implement binary search algorithm.

Answer: Binary search is an efficient algorithm for finding elements in a sorted array by repeatedly dividing the search interval in half.

Code Example:

Python

Diagram: Binary Search Process

goat

Mnemonic: "MCLR - Middle Compare, Left or Right adjust"

Question 4(a) OR [3 marks]

Explain concept of selection sort algorithm.

Answer: Selection sort is a simple comparison-based sorting algorithm that divides the array into sorted and unsorted regions.

Table: Selection Sort Characteristics

AspectDescription
ApproachFind minimum element from unsorted part and place at beginning
Time ComplexityO(n²) - worst, average, and best cases
Space ComplexityO(1) - in-place sorting
StabilityNot stable (equal elements may change relative order)
AdvantageSimple implementation with minimal memory usage

Mnemonic: "FSMR - Find Smallest, Move to Right position, Repeat"

Question 4(b) OR [4 marks]

Explain bubble sort method.

Answer: Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they're in the wrong order.

Table: Bubble Sort Characteristics

AspectDescription
ApproachRepeatedly compare adjacent elements and swap if needed
Passes(n-1) passes for n elements
Time ComplexityO(n²) - worst and average case, O(n) - best case
Space ComplexityO(1) - in-place sorting
OptimizationEarly termination if no swaps occur in a pass

Diagram: Bubble Sort Process

goat

Mnemonic: "CABS - Compare Adjacent, Bubble-up Swapping"

Question 4(c) OR [7 marks]

Explain the working of quick sort method with example.

Answer: Quick sort is an efficient divide-and-conquer sorting algorithm that works by selecting a pivot element and partitioning the array.

Table: Quick Sort Steps

StepDescription
1Choose a pivot element from the array
2Partition: Rearrange elements (smaller than pivot to left, larger to right)
3Recursively apply quick sort to subarrays on left and right of pivot

Example with Array [7, 2, 1, 6, 8, 5, 3, 4]:

Pivot: 4
After partition: [2, 1, 3] 4 [7, 6, 8, 5]
                 Left      P  Right

Recursively sort left: [1] 2 [3] → [1, 2, 3]
Recursively sort right: [5] 7 [6, 8] → [5, 6, 7, 8]

Final sorted array: [1, 2, 3, 4, 5, 6, 7, 8]

Diagram: Quick Sort Partitioning

Mnemonic: "PPR - Pivot, Partition, Recursive divide"

Question 5(a) [3 marks]

Explain binary tree.

Answer: A binary tree is a hierarchical data structure where each node has at most two children referred to as left and right child.

Diagram: Binary Tree

goat

Table: Binary Tree Properties

PropertyDescription
NodeContains data and references to left and right children
DepthLength of path from root to the node
HeightLength of the longest path from node to a leaf
Binary TreeEach node has at most 2 children

Mnemonic: "RLTM - Root, Left, Two, Maximum"

Question 5(b) [4 marks]

Define the terms root, path, parent and children with reference to tree.

Answer: Trees have specific terminology to describe relationships between nodes in the hierarchy.

Table: Tree Terminology

TermDefinition
RootTopmost node of the tree with no parent
PathSequence of nodes connected by edges from one node to another
ParentNode that has one or more child nodes
ChildrenNodes directly connected to a parent node

Diagram: Tree Terminology

goat

Mnemonic: "RPPC - Root at Top, Path connects, Parent above, Children below"

Question 5(c) [7 marks]

Apply preorder and postorder traversal for given below tree.

Answer: Preorder and postorder are depth-first tree traversal methods with different node visiting sequences.

Given Tree:

goat

Table: Tree Traversal Comparison

TraversalOrderResult for Given Tree
PreorderRoot, Left, Right40, 30, 25, 15, 28, 35, 50, 45, 60, 55, 70
PostorderLeft, Right, Root15, 28, 25, 35, 30, 45, 55, 70, 60, 50, 40

Code Example:

Python

Mnemonic: "PRE-NLR, POST-LRN - Preorder (Node-Left-Right), Postorder (Left-Right-Node)"

Question 5(a) OR [3 marks]

Enlist applications of binary tree.

Answer: Binary trees have numerous practical applications in various fields of computer science.

Table: Binary Tree Applications

ApplicationDescription
Binary Search TreesEfficient searching, insertion, and deletion operations
Expression TreesRepresenting mathematical expressions for evaluation
Huffman CodingData compression algorithms
Priority QueuesImplementation of heap data structure
Decision TreesClassification algorithms in machine learning

Mnemonic: "BEHPD - BST, Expression, Huffman, Priority queue, Decision tree"

Question 5(b) OR [4 marks]

Explain insertion of a node in binary search tree.

Answer: Insertion in a Binary Search Tree (BST) follows the BST property: left child < parent < right child.

Table: Insertion Steps in BST

StepDescription
1Start at the root node
2If new value < current node value, go to left subtree
3If new value > current node value, go to right subtree
4Repeat until finding an empty position (null pointer)
5Insert the new node at the empty position found

Diagram: BST Insertion

Mnemonic: "LSRG - Less-go-left, Same-or-greater-go-right"

Question 5(c) OR [7 marks]

Draw Binary search tree for 8, 4, 12, 2, 6, 10, 14, 1, 3, 5 and write In-order traversal for the tree.

Answer: Binary Search Tree (BST) is constructed by inserting nodes while maintaining the BST property.

Binary Search Tree for the given elements:

goat

Table: BST Construction Process

StepInsertTree Structure
18Root = 8
24Left of 8
312Right of 8
42Left of 4
56Right of 4
610Left of 12
714Right of 12
81Left of 2
93Right of 2
105Left of 6

In-order Traversal:

An in-order traversal visits nodes in the order: left subtree, current node, right subtree.

For the given BST, the in-order traversal is: 1, 2, 3, 4, 5, 6, 8, 10, 12, 14

Code Example:

Python

Mnemonic: "LNR - Left, Node, Right makes sorted order in BST"