Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

This repository is a compilation of my solutions to the Data Structures and Algorithms assignments offered by the University of California, San Diego (UCSD) and the National Research University Higher School of Economics (HSE) on Coursera. These assignments, covering material from courses 1 through 6, have all been solved using the Python.

TZhoroev/Coursera-Data_Structures_and_Algorithms

Folders and files, repository files navigation, coursera-data_structures_and_algorithms.

Plot

This repository contains my solutions to the Data Structures and Algorithms assignments offered by the University of California, San Diego (UCSD) and the National Research University Higher School of Economics (HSE) on Coursera. All of the problems from courses 1 through 6 have been solved using Python.

These solutions are intended to serve as a reference for those working on these assignments or seeking an alternative perspective on how to approach the problems. It is recommended that you try solving the assignments independently before consulting these solutions, as the best way to improve your skills is through practice. However, if you encounter difficulties or require additional guidance, these solutions are available for reference.

I hope that this repository proves to be a useful resource for your studies in data structures and algorithms.

Algorithmic Toolbox : Certificate

This online course covers basic algorithmic techniques and ideas for computational problems arising frequently in practical applications: sorting and searching, divide and conquer, greedy algorithms, dynamic programming.

Week 1: Welcome

  • Sum of Two Digits .
  • Maximum Pairwise Product .

Week 2: Algorithmic Warm-up

  • Fibonacci Number
  • Last Digit of a Large Fibonacci Number
  • Greatest Common Divisor
  • Least Common Multiple
  • Fibonacci Number Again
  • Last Digit of the Sum of Fibonacci Numbers Again

Week 3: Greedy Algorithms

  • Money Change
  • Maximum Value of the Loot
  • Car Fueling
  • Maximum Advertisement Revenue
  • Collecting Signatures
  • Maximum Number of Prizes
  • Maximum Salary

Week 4: Divide and Conquer

  • Binary Search
  • Binary Search with Duplicates
  • Majority Element
  • Improving Quick Sort
  • Number of Inversions
  • Organizing a Lottery
  • Closest Points

Week 5: Dynamic Programming I

  • Money Change Again
  • Primitive Calculator
  • Edit Distance
  • Longest Common Subsequence of Two Sequences
  • Longest Common Subsequence of Three Sequences

Week 6: Dynamic Programming II

  • Maximum Amount of Gold
  • Partitioning Souvenirs
  • Maximum Value of an Arithmetic Expression

Data Structures : Certificate

In this online course, we consider the common data structures that are used in various computational problems.

Week 1: Basic Data Structures

  • Check brackets in the code
  • Compute tree height
  • Network packet processing simulation
  • Extending stack interface
  • Maximum in Sliding Window

Week 2: Priority Queues and Disjoint Sets

  • Convert array into heap
  • Parallel processing
  • Merging tables

Week 3: Hash Tables and Hash Functions

  • Hashing with chains
  • Find pattern in text
  • Substring equality
  • Longest common substring
  • Pattern matching with mismatches

Week 4: Binary Search Trees

  • Binary tree traversals
  • Is it a binary search tree?
  • Is it a binary search tree? Hard version
  • Set with range sums

Algorithms on Graphs : Certificate

In this online course, first learned what a graph is and what are some of the most important properties. Then we learned several ways to traverse graphs and how one can do useful things while traversing the graph in some order. Then we learned shortest paths algorithms — from the basic ones to those which open door for 1000000 times faster algorithms used in Google Maps and other navigational services. We finished with minimum spanning trees which are used to plan road, telephone and computer networks and also find applications in clustering and approximate algorithms.

Week 1: Decomposition of Graphs I

  • Finding an Exit from a Maze
  • Adding Exits to a Maze

Week 2: Decomposition of Graphs II

  • Checking Consistency of CS Curriculum
  • Determining an Order of Courses
  • Checking Whether Any Intersection in a City is Reachable from Any Other

Week 3: Paths in Graphs I

  • Computing the Minimum Number of Flight Segments
  • Checking whether a Graph is Bipartite

Week 4: Paths in Graphs II

  • Computing the Minimum Cost of a Flight
  • Detecting Anomalies in Currency Exchange Rates
  • Exchanging Money Optimally

Week 5: Minimum Spanning Trees

  • Building Roads to Connect Cities

Week 6: Advanced Shortest Paths

  • Friend Suggestion
  • Compute Distance Faster Using Coordinates
  • Compute Distance with Preprocessing
  • Compute Distance with Preprocessing on Larger Road Networks
  • Travelling Salesman Problem

Algorithms on Strings : Certificate

Textual information abounds in the world and on the internet. We read webpages, books, emails, and textual inquiries to conduct information searches. From the perspective of computer science, each of those are strings. Search engines employ a variety of string algorithms to make sense of all that data and improve the effectiveness of searches. In addition, a variety of search methods are used in the developing field of personalized medicine to identify mutations in the human genome that cause disease. You will master important pattern matching ideas in this online course, including attempts, suffix trees, suffix arrays, and even the Burrows-Wheeler transform.

Week 1: Suffix Trees

  • Construct a Trie from a Collection of Patterns
  • Implement TrieMatching
  • Extend TrieMatching
  • Construct the Suffix Tree of a String
  • Find the Shortest Non-Shared Substring of Two Strings

Week 2: Burrows–Wheeler Transform and Suffix Arrays

  • Construct the Burrows–Wheeler Transform of a String
  • Reconstruct a String from its Burrows–Wheeler Transform
  • Implement BetterBWMatching
  • Construct the Suffix Array of a String

Week 3 & 4: Algorithmic Challenges: Suffix Arrays

  • Find All Occurrences of a Pattern in a String
  • Construct the Suffix Array of a Long String
  • Pattern Matching with the Suffix Array
  • Construct the Suffix Tree from the Suffix Array

Advanced Algorithms and Complexity : Certificate

Week 1: flows in networks.

  • Evacuating People
  • Assigning Airline Crews to Flights
  • Stock Charts

Week 2: Linear Programming

  • Infer Energy Values of Ingredients
  • Optimal Diet Problem
  • Online Advertisement Allocation

Week 3: NP-completeness

  • Assign Frequencies to the Cells of a GSM Network
  • Cleaning the Apartment
  • Advertisement Budget Allocation

Week 4: Coping with NP-completeness

  • Integrated Circuit Design
  • Plan a Fun Party
  • Reschedule the Exams

Week 5: Streaming Algorithms

  • Nice vs Naughty

Genome Assembly Programming Challenge : Certificate

Plot

Week 1: Assembling phi X174 Using Overlap Graphs

  • Assembling the phi X174 Genome from Error-Free Reads Using Overlap Graphs
  • Assembling the phi X174 Genome from Error-Prone Reads Using Overlap Graphs

Week 2: Assembling Genomes Using de Bruijn Graphs

  • Puzzle Assembly
  • Finding an Eulerian Cycle in Directed Graph
  • Finding a k-Universal Circular String
  • Assembling the phi X174 Genome from its k-mer Composition

Week 3: Genome Assembly Faces Real Sequencing Data

  • Finding a Circulation in a Network
  • Selecting the Optimal k-mer Size
  • Bubble Detection
  • Tip Removal
  • Assembling the phi X174 Genome from Error-Prone Reads using de Bruijn Graphs
  • Python 61.9%

Data Structures Assignment 1

(implementing a queue using stacks), due: aug 17.

This assignment is for you to get comfortable with JAVA features. You will get a chance to use class hierarchy, File I/O, Exception handling, Thread programming, Inter-thread synchronization etc. Please read the entire assignment carefully, many times over.

The goal is to implement a data structure called “queue” using another data structure called “stack”. Refer chapter 4 of the Goodrich and Tamassia book for stacks and queues.

Programming problem 1 : Implement a stack using an array. Implement the stack interface defined here . Use generics in Java to make sure that you can use the stack for any type of data. You may assume that the number of elements inserted into the stack never exceeds 100,000. Do NOT use the inbuilt Stack class of java. Name your stack implementation as myStack .

Queue using two Stacks

The goal of this assignment is to implement a queue using two stacks. We will employ two different ideas for this and try to understand why one idea is better than the other. Let us first consider a naive implementation.

Implementation 1:

Let S1 and S2 be the two stacks to be used in the implementation of our queue. All we have to do is to define the enqueue and dequeue operations for the queue.

enqueue ( T a)

            S1.push( a);

dequeue ( ){

            if (S1 is empty) return(error);

            while( S1 is not empty){

                        S2.push( S1.pop());

            }

            r <- S2.pop( );

            while( S2 is not empty){

                        S1.push( S2.pop());

return( r);

Programming Problem 2 : Use your stack implementation (programming problem 1) to implement a queue using the above pseudocode . Implement the queue interface defined here . Name your implementation myQueue1.

Implementation 2:

Again, let S1 and S2 be the two stacks to be used in the implementation of our queue. As in the previous implementation we have to define enqueue and dequeue operations.

            if (S1 is empty & S2 is empty) return(error);

            if (S2 is empty){

                        while( S1 is not empty){

                                    S2.push( S1.pop());

                        }

            return( S2.pop());

Programming Problem 3 : Use your stack implementation to implement a queue using the above pseudocode . Implement the queue interface defined here . Name this implementation myQueue2.

Analysis Problem 1 (not to be submitted) : Argue for yourself that the above two correctly implements a queue using two stacks.

Analysis Problem 2 (not to be submitted) : Try to figure out why the second implementation is much better than the first one.

Parallel Programming

This is an important programming paradigm where you can run multiple “threads” of execution in parallel. Parallel programming is useful in reducing the running time, or deal with asynchronous inputs, or sometimes just to model the problem in a better manner. Here we will use Java threads to get a taste of parallel programming.

Programming Problem 4 : You have to create multiple java threads (number of threads will be specified as input). Each thread will read from a separate file and execute the operation on a shared queue. You have to use the queue that you have made in programming problems 2 and 3. The implementation you have to use will be specified in the input. Note that you should make proper use of synchronization.

Input-output format for programming problems 4 : Programming problem 4 should use your implementations in programming problems 1 ,2 , and 3. We will not specifically check your implementation of programming problems 1 ,2 , and 3.

Program name : You must write a Simulate.java program which contains the main method. This is the program that we will run to check your implementations.

Input : Your program should take two command line arguments that are both integers. The first argument denotes the number of threads your program should run. The second argument tells you which implementation of a queue (myQueue1 or myQueue2) you should be using. For example, consider that you run the following command:

This means that you must run 5 threads and use your 1 st queue implementation (i.e., myQueue1).

The queue operations must be read from files named operations-x.dat . For example if there are 5 threads, thread 1 reads from operations-1.dat file, thread 2 reads from operations-2.dat file and so on. Each file contains enqueue and dequeue statements in separate lines. Following is an example of an operations-x.dat file:

<a>, <b>, etc. denote arbitrary strings.

Output : Your program should output two files. First it should produce a file named operations-out.dat which should contain the enqueue / dequeue operation and the thread number which executes this operation. For example suppose thread #1 executed enqueue ( a), dequeue (), enqueue (b), and then thread #2 executed dequeue (). Then your operations-out.dat file should be the following:

Your second file should be named output.dat and it should contain the output of the dequeue operations performed on the shared queue and the thread number performing the operation. For example, corresponding to the above operations-out.dat file, your output.dat file should be the following:

Your program must handle the errors in input file format as exception. These must be caught and reported on standard output as "FileFormatException".

Empty stack errors : In case of errors, for example, the queue is empty and there is a dequeue request. The output.dat file should contain the appropriate exception name for that request. For example, there is a single thread and the input file operations-1.dat is the following:

Then the output.dat file should look like:

  • DSA Tutorial
  • Data Structures
  • Linked List
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Divide & Conquer
  • Mathematical
  • Backtracking
  • Branch and Bound
  • Pattern Searching

Learn Data Structures and Algorithms | DSA Tutorial

  • Data Structures Tutorial
  • Array Data Structure
  • String in Data Structure
  • Linked List Data Structure
  • Stack Data Structure
  • Queue Data Structure
  • Tree Data Structure
  • Heap Data Structure
  • Hashing in Data Structure
  • Graph Data Structure And Algorithms
  • Matrix Data Structure
  • Introduction to Set – Data Structure and Algorithm Tutorials
  • Introduction to Map – Data Structure and Algorithm Tutorials
  • Advanced Data Structures

Algorithm Tutorial

  • Searching Algorithms
  • Sorting Algorithms
  • Recursion Algorithms
  • Backtracking Algorithm
  • Greedy Algorithms
  • Dynamic Programming or DP
  • What is Pattern Searching ?
  • Divide and Conquer
  • Mathematical Algorithms
  • Geometric Algorithms
  • Bitwise Algorithms
  • Randomized Algorithms
  • Branch and Bound Algorithm
  • Algorithms Tutorial

Competititve Programming

  • Competitive Programming - A Complete Guide

Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these technologies are better programmers than others and thus, crack the interviews of almost every tech giant.

DSA Full Form

The term DSA stands for  Data Structures and Algorithms , in the context of Computer Science.

Learn Data Structures and Algorithms | DSA Tutorial

What is DSA?

Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures.

How to learn DSA?

The first and foremost thing is dividing the total procedure into little pieces which need to be done sequentially. The complete process to learn DSA from scratch can be broken into 5 parts:

  • Learn at least one programming language (We leave this to your choice.)
  • Learn Data Structures

Learn Algorithms

  • Learn about Time and Space complexities
  • Practice Problems on DSA

How to learn DSA?

Hoping you have learned a programming language of your choice, let us move forward with the next step to learn DSA in this DSA tutorial.

Here comes the most important and the most awaited stage of the roadmap for learning data structure and algorithm – the stage where you start learning about DSA. The topic of DSA consists of two parts: 

  • Algorithms 

Though they are two different things, they are highly interrelated, and it is very important to follow the right track to learn them most efficiently. If you are confused about which one to learn first, we recommend you to go through our detailed analysis on the topic: What should I learn first- Data Structures or Algorithms?

Here we have followed the flow of learning a data structure and then the most related and important algorithms used by that data structure.

1. Learn Data Structures

Data structures  are essential components that help organize and store data efficiently in computer memory. They provide a way to manage and manipulate data effectively, enabling faster access, insertion, and deletion operations. Common data structures include  arrays, linked lists, stacks, queues, trees, and graphs  , each serving specific purposes based on the requirements of the problem at hand. Understanding data structures is fundamental for designing efficient algorithms and optimizing software performance.

Common Data Structures to learn:

Array is a linear data structure that stores a collection of elements of the same data type. Elements are allocated contiguous memory, allowing for constant-time access. Each element has a unique index number.

  • Traversal : Iterating through the elements of an array.
  • Insertion : Adding an element to the array at a specific index.
  • Deletion : Removing an element from the array at a specific index.
  • Searching : Finding an element in the array by its value or index.
  • One-dimensional array : A simple array with a single dimension.
  • Multidimensional array : An array with multiple dimensions, such as a matrix.
  • Storing data in a sequential manner
  • Implementing queues, stacks, and other data structures
  • Representing matrices and tables
  • Arrays Tutorial
  • Top 50 Array Coding Problems for Interviews
  • Practice problems on Arrays

A string is a sequence of characters, typically used to represent text. It is considered a data type that allows for the manipulation and processing of textual data in computer programs.

  • Concatenation : Joining two strings together.
  • Comparison : Comparing two strings lexicographically.
  • Substring extraction : Extracting a substring from a string.
  • Search : Searching for a substring within a string.
  • Modification : Changing or replacing characters within a string.
  • Text processing
  • Pattern matching
  • Data validation
  • Database management
  • String Tutorial
  • Top 50 String Coding Problems for Interviews
  • Practice Problems on String

3. Linked Lists

A linked list is a linear data structure that stores data in nodes, which are connected by pointers. Unlike arrays, linked lists are not stored in contiguous memory locations.

  • Dynamic : Linked lists can be easily resized by adding or removing nodes.
  • Non-contiguous : Nodes are stored in random memory locations and connected by pointers.
  • Sequential access : Nodes can only be accessed sequentially, starting from the head of the list.
  • Creation : Creating a new linked list or adding a new node to an existing list.
  • Traversal : Iterating through the list and accessing each node.
  • Insertion : Adding a new node at a specific position in the list.
  • Deletion : Removing a node from the list.
  • Search : Finding a node with a specific value in the list.
  • Singly Linked List : Each node points to the next node in the list.
  • Doubly Linked List : Each node points to both the next and previous nodes in the list.
  • Circular Linked List : The last node points back to the first node, forming a circular loop.
  • Linked lists are used in various applications, including:
  • Implementing queues and stacks
  • Representing graphs and trees
  • Maintaining ordered data
  • Memory management
  • Linkded List Tutorial
  • Top 50 Problems on Linked List for Interviews
  • Practice problems on Linked Lists

4. Matrix/Grid

A matrix is a two-dimensional array of elements, arranged in rows and columns. It is represented as a rectangular grid, with each element at the intersection of a row and column.

  • Rows : Horizontal lines of elements in a matrix.
  • Columns : Vertical lines of elements in a matrix.
  • Dimensions : The number of rows and columns in a matrix (e.g., a 3×4 matrix has 3 rows and 4 columns).
  • Element Access : Elements can be accessed using row and column indices (e.g., M[2][3] refers to the element in row 2, column 3).
  • Image processing
  • Data analysis
  • Optimization problems
  • Matrix/Grid Tutorial
  • Top 50 Problems on Matrix/Grid for Interviews
  • Practice Problems on Matrix/Grid

Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out) . LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first, comes out last.

  • Push : Adds an element to the top of the stack
  • Pop : Removes and returns the element at the top of the stack
  • Peek : Returns the element at the top of the stack without removing it
  • Size : Returns the number of elements in the stack
  • IsEmpty : Checks if the stack is empty
  • Function calls
  • Expression evaluation
  • Undo/redo operations
  • Stack Tutorial
  • Top 50 Problems on Stack for Interviews
  • Practice problems on Stack

A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of “ First in, First out ” ( FIFO ), where the first element added to the queue is the first one to be removed

  • Enqueue : Adds an element to the rear of the queue
  • Dequeue : Removes an element from the front of the queue
  • Peek : Retrieves the front element without removing it
  • IsEmpty : Checks if the queue is empty
  • IsFull : Checks if the queue is full
  • Circular Queue : Last element connects to the first element
  • Double-Ended Queue (Deque) : Operations can be performed from both ends
  • Priority Queue : Elements are arranged based on priority
  • Job scheduling
  • Message queuing
  • Simulation modeling
  • Data buffering
  • Queue Tutorial
  • Top 50 Problems on Queue for Interviews
  • Practice problems on Queue

A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is less than or equal to its own value. Heaps are usually used to implement priority queues , where the smallest (or largest) element is always at the root of the tree.

  • Insert : Adds a new element to the heap while maintaining heap properties.
  • Extract-Max/Extract-Min : Removes the root element and restructures the heap.
  • Increase/Decrease-Key : Updates the value of a node and restructures the heap.
  • Max-Heap : Root node has the maximum value among its children.
  • Min-Heap : Root node has the minimum value among its children.
  • Priority queues
  • Graph algorithms (e.g., Dijkstra’s algorithm)
  • Heap Tutorial
  • Top 50 Problems on Heap for Interviews
  • Practice Problems on Heap

Hashing is a technique that generates a fixed-size output (hash value) from an input of variable size using mathematical formulas called hash functions . Hashing is used to determine an index or location for storing an item in a data structure, allowing for efficient retrieval and insertion.

  • Hash Function : A mathematical function that maps an input to a hash value.
  • Hash Table : A data structure that stores key-value pairs, where the key is a hash value and the value is the actual data.
  • Collision : When two different keys produce the same hash value.
  • Division Method : Divides the input by a constant and uses the remainder as the hash value.
  • Mid Square Method: Squares the input and takes the middle digits as the hash value.
  • Folding Method : Divides the input into equal-sized blocks and adds them together to get the hash value.
  • Multiplication Method : Multiplies the input by a constant and takes the fractional part as the hash value.
  • Separate Chaining (Open Hashing) : Stores colliding elements in a linked list at the corresponding hash value.
  • Open Addressing (Closed Hashing) : Uses various strategies to find an alternative location for colliding elements within the hash table.
  • Efficiently storing and retrieving data in databases and file systems.
  • Verifying passwords and digital signatures.
  • Distributing requests across multiple servers.
  • Generating secure hashes for data integrity and authentication.
  • Hash Tutorial
  • Practice Problems on Hashing

A tree is a non-linear hierarchical data structure consisting of nodes connected by edges, with a top node called the root and nodes having child nodes. It is used in computer science for organizing data efficiently.

  • In-Order : Visit left subtree, current node, then right subtree.
  • Pre-Order : Visit current node, left subtree, then right subtree.
  • Post-Order : Visit left subtree, right subtree, then current node.
  • Classifications of Trees refer to grouping trees based on certain characteristics or criteria. This can involve categorizing trees based on their balance factor, degree of nodes, ordering properties, etc. Below are some important classification of Tree.
  • File systems
  • XML documents
  • Artificial intelligence
  • Tree Tutorial
  • Top 50 Tree Coding Problems
  • Practice problems on Tree

A Graph is a non-linear data structure consisting of a finite set of vertices(or nodes) and a set of edges that connect a pair of nodes.

  • Breadth-First Search (BFS) : Visits nodes level by level.
  • Depth-First Search (DFS) : Visits nodes recursively, exploring one branch at a time.
  • Social networks
  • Maps and navigation
  • Data mining
  • Graph Representation
  • Types of graphs
  • Graph Tutorial
  • Practice problems on Graph

Once you have cleared the concepts of Data Structures , now its time to start your journey through the Algorithms . Based on the type of nature and usage, the Algorithms are grouped together into several categories, as shown below:

1. Searching Algorithm

Searching algorithms are used to locate specific data within a larger set of data. It helps find the presence of a target value within the data. There are various types of searching algorithms, each with its own approach and efficiency.

  • Linear Search : Iterative search from one end to the other.
  • Binary Search : Divide-and-conquer search on a sorted array, halving the search space at each iteration.
  • Ternary Search : Divide-and-conquer search on a sorted array, dividing the search space into three parts at each iteration.
  • Jump Search
  • Interpolation Search  
  • Exponential Search  
  • Practice problems on Searching algorithm

2. Sorting Algorithm

Sorting algorithms are used to arranging the elements of a list in a specific order, such as numerical or alphabetical. It organizes the items in a systematic way, making it easier to search for and access specific elements.

There are a lot of different types of sorting algorithms. Some widely used algorithms are:

Related Topics:

  • Sorting Algorithm Tutorial
  • Top Sorting Interview Questions and Problems
  • Practice problems on Sorting algorithm

3. Divide and Conquer Algorithm

Divide and conquer algorithms follow a recursive strategy to solve problems by dividing them into smaller subproblems, solving those subproblems, and combining the solutions to obtain the final solution.

  • Divide : Partition the problem into smaller, independent subproblems.
  • Conquer : Recursively solve each subproblem.
  • Combine : Merge the solutions of the subproblems to obtain the final solution.
  • Merge Sort: Divides the array into two halves, sorts each half recursively, and merges the sorted halves.
  • Quick Sort: Selects a pivot element, partitions the array into two subarrays based on the pivot, and recursively sorts each subarray.
  • Binary Search: Divides the search space in half repeatedly until the target element is found or the search space is exhausted.

Related Articles:

  • Divide and Conquer Tutorial
  • Practice problems on Divide And Conquer algorithm

4. Greedy Algorithms

As the name suggests, this algorithm builds up the solution one piece at a time and chooses the next piece which gives the most obvious and immediate benefit i.e., which is the most optimal choice at that moment. So the problems where choosing locally optimal also leads to the global solutions are best fit for Greedy.

Some Important Problem of Greedy Algorithms are:

  • Greedy Algorithm Tutorial
  • Practice problems on Greedy algorithm

5. Recursion

Recursion is a programming technique where a function calls itself within its own definition. It is usually used to solve problems that can be broken down into smaller instances of the same problem. For Example: Towers of Hanoi (TOH) , Factorial Calculation and Fibonacci Sequence etc.

  • Base Case : Define a condition that stops the recursive calls and provides a solution.
  • Recursive Case : Define the steps to break down the problem into smaller instances and make recursive calls.
  • Return : Return the solution from the recursive calls and combine them to solve the original problem.

The point which makes Recursion one of the most used algorithms is that it forms the base for many other algorithms such as Tree traversals , Graph traversals , Divide and Conquers Algorithms and Backtracking algorithms .

  • Recursion Tutorial
  • Recursive Functions
  • Tail Recursion
  • Top 50 Problems on Recursion Algorithm for Interview
  • Practice problems on Recursion algorithm

6. Backtracking Algorithm

As mentioned earlier, the Backtracking algorithm is derived from the Recursion algorithm, with the option to revert if a recursive solution fails, i.e. in case a solution fails, the program traces back to the moment where it failed and builds on another solution. So basically it tries out all the possible solutions and finds the correct one.

Some important and most common problems of backtracking algorithms, that you must solve before moving ahead, are:

Related Article:

  • Backtracking Tutorial
  • Practice problems on Backtracking algorithm

7. Dynamic Programming

Dynamic Programming is a method used in mathematics and computer science to solve complex problems by breaking them down into simpler subproblems. By solving each subproblem only once and storing the results, it avoids redundant computations, leading to more efficient solutions for a wide range of problems.

Key Concepts:

  • Optimal Substructure : The optimal solution to a problem can be constructed from the optimal solutions to its subproblems.
  • Overlapping Subproblems : Subproblems are often repeated in the larger problem, leading to redundant computations.
  • Memoization / Tabulation : Storing the solutions to subproblems to avoid recomputation.

Some important and most common problems of dynamic programming algorithms, that you must solve before moving ahead, are:

  • Tabulation vs Memoization
  • How to solve a Dynamic Programming Problem?
  • Dynamic Programming Tutorial
  • Top 50 Dynamic Programming Coding Problems for Interviews
  • Practice problems on Dynamic Programming algorithm

8. Graph Algorithms :

Graph algorithms in data structures and algorithms (DSA) are a set of techniques and methods used to solve problems related to graphs, which are a collection of nodes and edges. These algorithms are designed to perform various operations on graphs, such as searching, traversing, finding the shortest path , and determining connectivity . They are essential for solving a wide range of real-world problems, including network routing, social network analysis, and resource allocation.

  • Top 50 Graph Coding Problems for Interviews
  • Practice Problem on Graph Algorithms

9 . Pattern Searching

Pattern searching is a fundamental technique in DSA used to find occurrences of a specific pattern within a given text.

Below are some some standard pattern searching algorithms:

  • Pattern Searching Tutorial
  • Practice Problem on Pattern Searching

10 . Mathematical Algorithms

Mathematical algorithms are a class of algorithms that solve problems related to mathematical concepts. They are widely used in various fields, including Computer graphics, Numerical analysis, Optimization and Cryptography.

  • Practice Problem on Mathmatical Algorithm

11. Geometric Algorithms

Geometric algorithms are a class of algorithms that solve problems related to geometry. Geometric algorithms are essential for solving a wide range of problems in computer science, such as:

  • Practice Problem on Geometric Algorithms

12. Bitwise Algorithms

Bitwise algorithms are algorithms that operate on individual bits of numbers. These algorithms manipulate the binary representation of numbers to perform tasks such as bit manipulation, bitwise logical operations (AND, OR, XOR), shifting bits , and setting or clearing specific bits within a number. Bitwise algorithms are commonly used in low-level programming, cryptography, and optimization tasks where efficient manipulation of individual bits is required.

  • Bitwise Algorithms Tutorial
  • Practice Problem on Bitwise Algorithms

13. Randomized Algorithms

Randomized algorithms are algorithms that use randomness to solve problems. They make use of random input to achieve their goals, often leading to simpler or more efficient solutions.

Types of Randomized Algorithms:

  • Las Vegas : Always produces a correct result, but the running time is random.
  • Monte Carlo : May produce an incorrect result with a small probability, but the running time is usually faster.

Important Algorithms that uses Randomization Algorithms:

14. Branch and Bound Algorithm

The Branch and Bound Algorithm is a method used in combinatorial optimization problems to systematically search for the best solution. It works by dividing the problem into smaller subproblems, or branches, and then eliminating certain branches based on bounds on the optimal solution. This process continues until the best solution is found or all branches have been explored.

Standard Problems on Branch and Bound Algorithm:

  • Branch and Bound Algorithm Tutorial

Learn about Complexities

In Data Structures and Algorithms (DSA), the main goal is to solve problems effectively and efficiently. To determine the efficiency of a program, we look at two types of complexities:

  • Time Complexity : This tells us how much time our code takes to run.
  • Space Complexity : This tells us how much memory our code uses.

Asymptotic Notation :

To compare efficiencies of algorithms, we use asymptotic notation, a mathematical tool that estimates time based on input size without running the code. It focuses on the number of basic operations in the program.

The most commonly used notation for code analysis is Big O Notation , providing an upper limit on the running time or memory usage concerning the input size.

  • Understanding Time Complexity with Simple Examples
  • Time complexities of different data structures
  • How to Analyse Loops for Complexity Analysis of Algorithms
  • Practice Questions on Time Complexity Analysis

Practice Problem Cheat Sheets:

Curated lists of problems from below articles:

  • DSA Roadmap by Sandeep Jain
  • SDE SHEET – A Complete Guide for SDE Preparation
  • GeeksforGeeks Master Sheet – List of all Cheat Sheets

Please Login to comment...

Similar reads.

  • DSA Tutorials

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Assignment 1: JavaScript fundamentals

Due thu apr 20 11:59pm pt.

Submissions not accepted after Sat Apr 22 11:59pm PT .

Backstory: As you embark on your web development journey, you decide to set your sights on something we can all get behind: fixing Axess! And hey, those systems are probably so broken that we may as well start from scratch, right? But before you can take on course enrollments, you'll need a few building blocks first. Besides, as we come up on commencement, maybe you can build up your reputation as a reliable web developer by helping out with that.

This assignment will have you practice some fundamental JavaScript concepts and how to use them in the browser. You'll build a small app to simulate students declaring their major and graduating.

Learning goals

After completing this assignment, you will be able to

  • Write functions and classes in JavaScript that manipulate various types and data structures,
  • Create modules that import dependencies,
  • Create a small HTML page with form elements, and
  • Use JavaScript to respond to user events and read form controls.

Getting started

As with assignment 0, follow these steps to get started.

  • Download the starter code and extract the .zip file's contents.
  • Open your command line and navigate to the extracted assign1 directory.
  • Run npm install .
  • Run npm start to start the web server.
  • Open localhost:1930 in your web browser.

Deliverables: We've tried to use boxes like this one to highlight the specific tasks you will need to complete for the assignment. These boxes won't stand alone without the rest of the handout, but consider, for example, using them as a checklist to make sure you've done everything.

Part 1: Warmup exercises

The first part of the assignment consists of a few short warmup exercises, designed to give you practice with JavaScript data structures.

You will write your answers in warmups.js , which has already been included in index.html . We have provided a function testWarmups() , callable from the console, to check your answers.

Task 1a: Using the debugger

The first task will give you practice using the debugger.

  • To begin, please make sure you replace the TODO in the import line at the top of warmups.js with your SUNetID (login name, not number).
  • The function debugExercise calls checkAnswer , passing it a "secret code." Your task is to determine the correct code to pass. But since checkAnswer is being imported from debugme.js , located outside of your assign1 folder, you won't be able to modify it (in order to, for example, add a console.log ).
  • Use the debugger to look at the JavaScript code for checkAnswer . Then, call debugExercise from the console and stop the function while it is running so you can inspect the values of the relevant variables to determine what you must pass to it.
  • Once you have the secret code, replace the TODO in the argument to checkAnswer . Rerunning debugExercise should print a "Success!" message.
  • Finally, fill in the comment in debugExercise with a brief (1-2 sentence) explanation of your strategy: how did you enter the debugger, and where did you stop? How did you read the secret code?

Some notes for this task:

  • The list of files in the Sources tab is split up by where the files are located. You'll find debugme.js under web.stanford.edu .
  • The secret code is a short string of random characters, different for each student. The script that generates it uses some advanced JavaScript features, so we've tucked it away in another file. You may look at the file if you'd like, but it's not necessary (and probably won't help you get the answer).
  • This being the web and JavaScript, there are ways to "circumvent the process" and solve the task without the debugger. We ask that you avoid these unintended alternate strategies, both because we think the debugger is a valuable tool to have in your toolbox, and because we expect that solving the task using the debugger will be much easier. If, after following the process we've outlined, you want to think about how you might solve it a different way, feel free.

Task 1b: Working with data structures

For the rest of this assignment, you'll work with data for a few sample students and departments.

First, open data.js to have a look at the provided data. The file exports a single JavaScript Object with three entries:

  • students is an Array of Objects, each object representing a student. A student object contains their givenName , their surname , and their sunetid . (Note: These aren't the CAs' actual SUNetIDs.) You can assume that SUNetIDs will be unique across all students in the array.
  • depts is an Array of Objects. Each object contains information about a department: its name (like "Computer Science") and its code (like "CS").
  • units is an Object mapping student SUNetIDs (keys) to the number of units that student has completed (values). You may assume that there will be one entry in the object for each student in students .

This data object has been imported into warmups.js as the variable DATA . Once you have reviewed the data, fill in the functions in warmups.js , using DATA , as follows:

  • firstNSunets returns the SUNetIDs of the first n students ( n is a parameter to the function) in the students array. You can assume there are at least n students.
  • shortDeptCodes returns an Object whose keys are department names and whose values are their corresponding codes. But only include a department in the result if its code is exactly two characters long.
  • averageUnits returns the average number of units completed by all students in the data. You can assume there will be at least one student, and you don't need to round or truncate the result.

Each function should be relatively short and will involve some form of iteration. Once you have written these functions, you can use testWarmups (which is exposed to the console) to check that your answers match what we expect.

Note on style and style checking

To help identify some common style issues (and a few functionality issues too), we have includes a configuration file for ESLint .

If you are using VSCode and have installed the ESLint extension, these issues should be highlighted automatically as you code. (If you aren't seeing any highlights, you may have to restart VSCode after you do npm install .)

If you are using something else, or would like to check for lint errors manually, you can run npm run lint in your terminal (you'll have to do this in a different window than the one you ran npm start in).

Note that ESLint won't catch all (or indeed most) style issues. We will give you specific style feedback on your assignment through grading. But having a clean lint run is a good first step!

Part 2: Modeling students and departments

For the remainder of the assignment, you will work with the various other .js files in the public folder. All of these files are imported by index.js . We have included index.js in the provided HTML.

Your next task is to implement two JavaScript classes which we will use to model students and departments in our app.

Task 2a: Student class

Implement the Student class in student.js , and export it as the default (and only) export. An instance of Student will have the following properties (instance variables), which are all "public":

  • sunetid : The student's SUNetID
  • givenName : The student's given name
  • surname : The student's surname
  • dept : The name of the department the student is declared in (a string), or null if the student has not declared yet
  • unitsCompleted : The number of units the student has completed (a number)
  • isAlum : true if the student has graduated, false if not

An instance has the following methods (with corresponding signatures):

  • constructor(sunetid, givenName, surname) : Construct a new Student . The student's SUNetID, given name, and surname are as passed in. Students start undeclared, ungraduated, and with zero units completed.
  • fullName() : Return the student's full name, which is their given name, followed by a space, followed by their surname.
  • addUnits(units) : Increase the number of units the student has completed by the parameter units .
  • toString() : Return a string representing the student, which should be their given name, a space, their surname, another space, and their SUNetID in parentheses. (For example, "Michael Chang (mchang91)")
  • canGraduate() : Return a boolean indicating whether the student can graduate. A student can graduate if they have declared and have completed at least 180 units. If the student has already graduated, this method should throw an Error with a descriptive message.

Task 2b: Department class

Now write the Department class and export it as the default export in dept.js . An instance of Department has the following "public" properties:

  • name : The full name of the department
  • code : The department code
  • students : An array of the current (non-alum) students who have declared under this department

Implement the following methods:

  • constructor(name, code) : Construct a new department with the name and code passed in. Departments start with no current students.
  • toString() : Return the string representation of the department, which is just the department's name.
  • declare(student) : Declare the passed-in Student instance under this department, updating the student's and department's instance variables accordingly. If the student is already declared under this department, this method should return without doing anything. But if the student is already declared under a different department, this method should throw an Error with a descriptive error message.
  • graduate() : Check if each current student in the department can graduate; if they can, mark them as an alum and remove them from the list of current students. Return an array of the just-graduated Student instances.

Some notes on these tasks:

  • You may add additional instance variables and methods to these classes if you wish, but you are not required to.
  • It is a good practice to reuse existing functionality where possible. For example, notice how a Student 's toString contains their full name.
  • You may assume that a client of these classes will not modify the instance variables in a way that makes the instance inconsistent. For example, a client will not directly set a student's dept without going through declare .
  • You aren't required to do any error checking beyond what is described here.
  • Review the end of lecture 3 for the syntax for throwing Error s. Your errors should generate exceptions that can be caught and handled by the client of your class (which you will do in the next part).

Part 3: The App class

Finally, you'll put this app together by implementing the App class (in app.js ).

Task 3a: Console interface

An instance of the App class is constructed by index.js when the page loads. App has the following instance variables:

  • students : An Object mapping students' SUNetIDs (keys) to corresponding Student instances.
  • depts : An Object mapping department codes (keys) to corresponding Department instances.

The constructor has been started for you; you will add to it in the next task. First, implement the following methods:

  • First, reset the students and depts instance variables to be empty. This allows loadData to "reset" the app.
  • Populate the students map with new Student instances, using the students data.
  • Update the number of units each student has completed via the units data.
  • Populate the depts map with new Department instances, based on the passed-in data.
  • declare(sunetid, deptCode) : Takes a SUNetID and department code (both strings) and tries to declare that student under that department, then returns the (updated) Student instance. If the SUNetID or department code isn't known to the app, throw an Error with a descriptive message. (If calling declare on the Department causes an error, don't handle it here.)
  • graduate(deptCode) : Make the department specified by the passed-in code try to graduate its students, returning the list of graduates ( Student instances). If the department code doesn't match a known department, throw an Error with a descriptive message.

You will also need to add imports for Student and Department .

After completing these methods, you will be able to test your app from end to end:

  • The app instance is exposed to the console. You can inspect its instance variables and call its methods.
  • For example, you could call app.declare(“mchang91", "CS") or app.graduate(“BOGUS") . (Note that loadData is already called for you in index.js .)
  • The function testApp , exposed to the console, will attempt to test a variety of methods from part 2 and this task. If anything doesn't match, it will print out an error message. These tests aren't comprehensive, and we encourage you to add some more tests of your own.

Task 3b: User interaction on the page

Your final task of this assignment is to expose the declare and graduate methods you just wrote to a user of the web page:

  • Edit the HTML to add a form with two inputs, one for SUNetID and one for department code. These inputs should be labeled so they are identifiable, and make sure to give them id s so you can reference them in JavaScript.
  • Add two buttons to the form, one for "Declare" and one for "Graduate".
  • When the user types in a SUNetID and department code and clicks "Declare", call your app's declare method with the entered values.
  • If the declaration is successful, display an alert informing the user, including the student's name and the department name. For example, "Michael Chang (mchang91) declared Computer Science!"
  • If the declaration fails, display an alert with the error message. (Note: It's not enough for the error to be printed to the console, since users won't think to look there. You must catch the error and present it via alert .)
  • Similarly, implement the "Graduate" button. This button ignores the entered SUNetID. Upon success, display an alert listing the students who graduated. For example, Graduates: Neel Kishnani (neelk) Jason Chuen (jahchuen) (You can use \n to add a newline in alert messages.)

Some notes on this task:

Screenshot of form controls and buttons

  • You will need to add additional methods to App and are free to add instance variables as well. But you should mark them as "private" by prefixing them with an underscore (_).
  • Recall from lecture 4 that you can access the forms on a web page using document.forms , and you can reference the controls of a form using their id or a property of the form.
  • Remember that a <button>l; inside of a <form> defaults to having type="submit" , meaning it will refresh the page when clicked. You'll want to change its type to button to avoid this.
  • Don't forget to bind your event handlers! As seen in lecture 4, it is best practice to do this in the constructor (and this is preferred over creating functions on the fly.)

When you are finished, please remember to delete your node_modules folder , and then submit your assign2 folder to Paperless .

Assignment 1

Type: Individual Assignment

Due: by 9:30 PM on Wednesday, September 12, 2018

Part 1: Background and Logistics

Java basics, your assignment, grading and other information.

  • Read the course syllabus and familiarize yourself with the course schedule .
  • Complete the background questionnaire .
  • Enroll in th Piazza course and explore its features.
  • Do the assigned Reading 1 for 9/12 and post at least one question you have about it to the corresponding folder reading1 on Piazza. Note that you will need to do this for each assigned reading on the course schedule for the whole term. You are also encouraged to post questions unrelated to readings (try to put them in an appropriate folder) and help answer questions posted by your classmates!

Part 2: Comparing Java with Python

The goal of this part is to help you to understand the similarities and differences between Java and Python and to prepare you to starting writing your own Java programs. Some of you may have learned Java in your first CS course, rather than Python. This assignment will still contain useful information about the process of learning a second language.

Learning your second programming language is different from learning your first. Assuming your first language was something relatively standard these days (Python, Scala, C, C++, etc.) you start out already knowing about many of the nearly-universal language constructs: assignments, loops, conditionals, functions, operators, classes, etc. Learning the second language involves a lot of learning new syntax for old ideas, rather than learning both the ideas and the syntax at the same time. As a result, learning your second language typically goes more quickly than learning the first. The more languages you learn, the faster you will get at this process.

For this class, I will assume that you are making a transition from Python (which we teach in CS 111) to Java (which we will use in CS 201). In fact, I imagine that a few of you met Java in high school, and some of you may even have skipped CS 111 and thus do not know Python. If you’re one of the latter and you plan to take courses beyond CS 201, you’ll eventually want to start teaching yourself Python, for which you may find some of these exercises useful in a backwards sort of way.

During the first few days of class, we’re going to focus our attention on the differences between Python and Java to help get you started in Java, and you may find Ken Lambert’s from Python to Java tutorial a useful resource for this. Some key differences include:

  • Explicit types (e.g. int , double , String , …) are specified for all variables, parameters, return values, etc.
  • There’s an awkward distinction between “primitive types” ( int , short , long , float , double , byte , char , boolean ) and “reference types” (everything else).
  • Program structure requires the use of classes. This was optional in Python. Braces {} are used instead of indentation to delimit if / else / for / while /etc. bodies (though indentation remains an essential element of good programming style).
  • Miscellaneous syntactical differences: semi-colons ( ; ) are used to terminate instructions, // and /*...*/ for comments, only "" for string literals (you can’t use single quotes), try / catch for exceptions, etc.
  • No easy built-in lists [] or dictionaries {} .

For each of the Python/Java program pairs,

  • read the programs,
  • run the programs (both Python and Java), and
  • write down questions you have about the Java code.

Note: there are some questions and exercises in the comments of some of the programs that you should try. Remember that to run the Java programs, you need to compile them first:

Then you can run the compiled class:

The Python programs are written for Python 3, so run them with:

When you’re done, post your questions (and answers if you have them!) to the assignment1 folder on Piazza.

Take this exercise seriously. Figure out what you know, what you don’t know, what’s easy, what’s confusing, etc. If you pay careful attention to these starter programs, you’ll have a great start on writing your own Java programs. You may find it helpful to do this exercise in conjunction with the readings for this week. The appendices of your book may be able to help you answer some of your or your classmates’ questions, and looking at these examples may help you recognize what parts of the reading you already know and what you should consider more closely.

Below is the list of program pairs. You can also download a zip file that contains all of the files.

  • Hello World: hello.py , Hello.java
  • Conditionals: conditionals.py , Conditionals.java
  • Line Reader: linereader.py , LineReader.java
  • This is a version of Line Reader where the file is specified using a command-line argument instead of being hard-coded into the source.
  • Lists: lists.py , Lists.java
  • Loops: loops.py , Loops.java
  • N-Sided Die: die.py , Die.java

This assignment is graded entirely on participation; the absolute baseline is that you post two questions of your own and reply to two others’ questions to the assignment1 folder on Piazza, but you are encouraged to post more! Note that I may address your questions in class for this assignment rather than on Piazza.

Java is installed in the computer labs on campus (both in the CMC and elsewhere). You are welcome to install Java on your own computer as well using these instructions on the CS department website. Note that the only officially supported environment is the lab computers, but Mike Tie ( [email protected] , CMC 305) can help you troubleshoot if you run into problems installing Java on your home computer; I’m also happy to try to help you during office hours if you run into problems.

Start early, ask lots of questions, and have fun! Don’t hesitate to ask me, the prefect, or the lab assistants for help if you’re struggling!

  • CGPA calculation updated in INFO student query section.
  • Note added in SHARE query section.
  • Sample query and result text file updated.
  • Java version to be used added in Important notes section.
  • Result of SHARE 2015cs1325 COL106 query is updated.
  • Signature of gradepoint function in GradeInfo_ interface is updated
  • Course file updated. Title of course COL113 updated to Distributed Systems
  • Implementation of gradepoint function in GradeInfo_ interface is added.
  • "You must not use any integer constant in your code." is removed from the description.
  • CGPA formula added for reference in INFO student query section.
  • README file should be added in src folder.
  • Deadline extended to 9th Aug(Friday), 11:55 P.M
  • Interface GradeInfo_ updated with grade() function >>
  • Test cases uploaded for reference Download from here .

You may only use external packages java.util.Iterator and java.io.* for this assignment.

· First, implement the following LinkedList_ interface, which uses a Position_ interface:

A student has three entities: department, hostel and courses. In this assignment, you are required to maintain at least these three linked lists to manage these entities: allHostels includes all hostels, allDepartments includes all departments and allCourses includes all courses. In addition, each element in the lists allHostels, allDepartments, allCourses itself should maintain lists that includes all students in that hostel, department, or course, respectively. · In order to organize these entities, use interface Entity_ :

· You may implement classes Hostel , Department , and Course , which are derived from Entity_ . You must also implement interface Student_ :

· Finally, implement a public class Assignment1 , with a static main that has two parts: private static functions getData and answerQueries . The main method takes as command line argument three strings; each string is a file name. The first file (student record file) contains personal data about the students, the second (course file) contains the list of courses taken by students, and finally the third (student query file) contains some queries to process. The first two files are passed to the method getData. The third file is processed by the method answerQueris. i

getData reads information per student from the specified student record file and course file, inserting the information in the respective linked lists (e.g., allHostels, allDepartments, allCourses), updating all data structures.

Student record file will contain record details of student in this order: entry number, name, department, and hostel. These names are single word strings, separated by space (See examples later). Every line contains one record of one student. The student record file will hence act as your source of student information.

The course file lists on each line the grade of one student in one course. It has four strings: the first indicates the student's unique entry number, the second indicates the course number with no spaces (e.g., COL106), the letter grade, and the course title. The title may have multiple words (space separated).

Note that the type of entity will be inferred from an entity name. Entity names are unique. In other words, if a department is named cse , no course or hostel would be named cse . But there will be extra credit for handling non-unique names. In such case, the query should count all students that are common to all entities named cse . !-->

cgpa

Submission instructions

Please ensure that you follow the following set of instructions meticulously while submitting the assignment on Moodle. Also, please note that in case of deviation from this procedure will render your submission faulty, and your assignment might not be evaluated at all by the script. Please follow these steps:

  • On eclipse, by default, all your source files (.java files) are saved into a directory called "src" inside your project. You have to compress this directory (to zip format) and rename the zip file in this format: your-entry-number_assignment1.zip Example: If your entry number is 2012CSZ8019, the zip file should be named 2012CSZ8019_assignment1.zip. It should expand to a directory called src , which contains all your .java files. Please make sure that you follow exactly this naming format.
  • Next, convert the zip file to base64 format. On any linux system, you can do this easily by issuing the following command on the terminal : base64 entrynumber_assignment1.zip > entrynumber_assignment1.zip.b64 This will create a file with the same name with a b64 extension appended at the end.
  • Upload this b64 file on moodle and submit it (in the "Submission" section). After Submission, there is an option of "Evaluate" in the "Edit" section. Click on "Evaluate". On the right side of the window, you will get information about the submission status. On clicking the "Evaluate" link, you should see a script running and producing an output of your codes' performance against the standard set of test cases that we supply internally for the assessment. A dialog box will show you the messages on how your codes performed against the benchmarks that we provided.
  • Please note that the immediate feedback is based on simple checks and to inform you whether your java code produces some right output for a basic test case. It is not the real grading. Hence, the grade that you see at submission is only to indicate if submission succeeded. During the actual evaluation, we will run many other tests and provide the final grade based on those. That grade will be uploaded on moodle after grading.
  • Please do not submit any executable or other types of files along with the source code. The "src" directory should only contain your code (.java) files and README file. Information about README file is present in Submission Requirements of course home page.
  • As you approach the deadline for assignment submission, multiple students will submit their files together. As a result, the server will be slow to respond to clicks on "Evaluate" link. In fact, we may even turn off the immediate feedback (Evaluate) option up to an hour before the submission in case of excessive load. You should submit well in advance to check for basic gradability. You may always modify and re-submit your assignment until the deadline. In any case, when the response to "Evaluate" request is slow, please be patient and re-try after 30 seconds. Incessant clicking will only make it worse. Please also note that no emails regarding slow response to "Evaluate" will be entertained on the day of submission.
  • Note that you must click on "Evaluate" after you submit the b64 file. Submitting the file without clicking on "Evaluate" may mean that your code does not meet the desired specifications. In that case, your submission will not be evaluated for the assignment.

Dept. of Computer Sc. & Engg. IIT Delhi Bharti Building 422 New Delhi 110016 Ph. (+91) 11 2659-6032

Browse Course Material

Course info.

  • Prof. Erik Demaine

Departments

  • Electrical Engineering and Computer Science

As Taught In

  • Algorithms and Data Structures

Learning Resource Types

Advanced data structures, assignments.

  • There will be a weekly one-page assignment, 10 assignments in total.
  • You may skip any one problem, or we will ignore the problem with the lowest grade. If you volunteered to scribe twice, we will ignore the lowest two grades.
  • The answers must be typeset in LaTeX. The answers must fit in one page, or your solution will not be read. Use at least 10 pt font and 1 inch margins. This rule is meant to prepare you for writing research publications: one often has to explain great ideas in a very limited number of pages.
  • Submissions must be made online and consist of a compiled PDF document.
  • Grades and comments will be posted online.
  • Solutions do not need to include all calculations, trivial details etc. Just prove to us that you found the solution, and you understand it well.
  • 0 = You didn’t get it. Filling one page to the brim does not mean you can’t get zero. Please don’t write stuff you know is wrong.
  • 1 = Your solution was ultimately a good one, but the write-up contained significant errors or omissions.
  • 2 = (We think) you got it.

facebook

You are leaving MIT OpenCourseWare

Archived Content

Perplexing puzzles.

Solo MP This MP, as well as all other MPs in CS 225, are to be completed without a partner.

You are welcome to get help on the MP from course staff, via open lab hours, or Piazza!

Goals and Overview

In this MP, you will:

  • Work with a graph that is to large too store completely in memory
  • Use a graph algorithm to solve a complex problem
  • Implement an algorithm from public sources documents
  • See the difference in performance between a guided and unguided search algorithm

Checking Out the Code

All assignments will be distributed via our release repo on github this semester. You will need to have set up your git directory to have our release as a remote repo as described in our git set up

You can merge the assignments as they are released into your personal repo with

if you are using multiple machines you may need to use the following to allow them to work correcly.

The first git command will fetch and merge changes from the main branch on your remote repository named release into your personal. The --no-edit flag automatically generates a commit message for you, and the --no-rebase flag will merge the upstream branch into the current branch. Generally, these two flags shouldn’t be used, but are included for ease of merging assignments into your repo.

The second command will push to origin (your personal), which will allow it to track the new changes from release .

You will need to run these commands for every assignment that is released.

All the files for this mp are in the mp_puzzle directory.

Preparing Your Code

This semester for MPs we are using CMake rather than just make. This allows for us to use libraries such as Catch2 that can be installed in your system rather than providing them with each assignment. This change does mean that for each assignment you need to use CMake to build your own custom makefiles. To do this you need to run the following in the base directory of the assignment. Which in this assignment is the mp_puzzle directory.

This first makes a new directory in your assignment directory called build . This is where you will actually build the assignment and then moves to that directory. This is not included in the provided code since we are following industry standard practices and you would normally exclude the build directory from any source control system.

Now you need to actually run CMake as follows.

This runs CMake to initialize the current directory which is the build directory you just made as the location to build the assignment. The one argument to CMake here is .. which referes to the parent of the current directory which in this case is top of the assignment. This directory has the files CMake needs to setup your assignment to be build.

At this point you can in the build directory run make as described to build the various programs for the MP.

You will need to do the above once for each assignment. You will need to run make every time you change source code and want to compile it again.

Assignment Description

data structures assignment 1

In this mp we will be developing a puzzle solver for 15 puzzle as a graph problem. If you have not heard of 15 puzzle before you may want to look at the wikipedia article on it here . We will then generate an animation of the solution.

Part 1: The PuzzleState data structure

In the first part of this assignment we will work on representing the puzzle as a graph. To do this we will have a node for every possible position of the puzzle and an edge between two nodes if there is a single move of a tile that will move from one position to the next. The tricky part in this is that there are 16 factorial possible positions for the puzzle. Since this is way too large to store in memory we will need to only use the portions of the graph that we need to get from the starting position until we can find a solution.

To do this we will build a class PuzzleState that stores a single vertex of the graph but can also create its neighbors when asked. This is not hard to do since the possible positions you can move to are easy to compute only knowing the current position. This will give you a system where you only need to create the nodes of the graph when you explore them. You will need to implement all the methods in the PuzzleState class.

Creating and Outputing

While the internal implementation of the PuzzleState class is entirely up to you we are defining two functions to make sure that we agree on what state we are referring to. These functions are the Constructor that takes an array of positions and creates a PuzzleState with those positions and asArray which returns the array version of that state. The format of this is to list the values in the puzzle starting for the upper left hand corner and moving to the right until the end of the line then moving to the next line until all 16 positions are provided.

Implementing operator<

To ensure that you can use std::map to store PuzzleStates we require you to implement an operator<() . While this operator does not represent any real relation between the different puzzle states it will satisfy the requirement for a total order so that you can use std::map .

Manhattan Distance

One function that might be unclear is the manhattanDistance function. This is asking you to compute a distance value between two states. This distance is the distance that each tile has to travel in the x dimension and the y dimension to reach the location of the tile in the other state.

Testing Your Code

Provided Catch test cases are available as well by running:

Extra Credit Submission

For extra credit, you can submit the code you have implemented and tested for part one of mp_puzzle. You must submit your work before the extra credit deadline as listed at the top of this page. See Handing in Your Code for instructions.

Part 2: The Solve Functions

In part 2 we are writing two different functions that will each solve the puzzle by finding the shortest path from the start state to the goal state. If the goal is not stated, the standard solved state will be used. The first version will solve this by implementing breadth first search. The second will use the A* algorithm. The doxygen of these functions can be seen here solveBFS and solveAstar .

A* search Algorithm

The A* algorithm is an algorithm for finding the shortest path from one point in a graph to another point in the graph. Documentation on the general algorithm can be found on wikipedia here . You should use the material provided there as the basis for your implementation. The key idea here is that A* uses a heuristic function to estimate how much further a state is from the goal state. In our case we will be using the manhattan distance function we wrote in part 1. This works since each move in the puzzle moves a single piece in a single direction so the minimum distance from a state to the goal state is enough moves to move each piece directly there.

Handing in your code

You must submit your work on PL for grading. We will use the following files for grading:

All other files will not be used for grading.

  • Study Guides
  • Homework Questions

Assignment 1 - Database Basics - copia

  • Information Systems

IMAGES

  1. Data Structures: Assignment 1

    data structures assignment 1

  2. Assignment 1 Using the JCF

    data structures assignment 1

  3. Assignment 1.docx

    data structures assignment 1

  4. Data Structures , week 1 Programming Assignment Answers

    data structures assignment 1

  5. Data Structures Assignment Help by top programmers

    data structures assignment 1

  6. Solved Data Structures Assignment 1 ( 10 marks) Q1) Apply

    data structures assignment 1

VIDEO

  1. Data Structure Programming : Unit 4-1

  2. CS301 Data Structures Assignment 1 Fall 2023 Virtual University of Pakistan

  3. NPTEL The Joy of Computing using python week 6 all 3 programming assignment answer with link of code

  4. Python Data Structures Assignment 10.2 Solution [Coursera]

  5. Data Structures and Algorithms

  6. Video Assignment

COMMENTS

  1. Coursera-Data_Structures_and_Algorithms

    This repository contains my solutions to the Data Structures and Algorithms assignments offered by the University of California, San Diego (UCSD) and the National Research University Higher School of Economics (HSE) on Coursera. All of the problems from courses 1 through 6 have been solved using Python. These solutions are intended to serve as a reference for those working on these assignments ...

  2. PDF Programming Assignment 1: Basic Data Structures

    Programming Assignment 1: Basic Data Structures Revision:March29,2020 ... In this programming assignment, you will be practicing implementing basic data structures and using them to solve algorithmic problems. In some of the problems, you just need to implement and use a data

  3. Data Structures

    Module 1 • 4 hours to complete. In this module, you will learn about the basic data structures used throughout the rest of this course. We start this module by looking in detail at the fundamental building blocks: arrays and linked lists. From there, we build up two important data structures: stacks and queues.

  4. Data Structures Assignment 1

    Please read the entire assignment carefully, many times over. The goal is to implement a data structure called "queue" using another data structure called "stack". Refer chapter 4 of the Goodrich and Tamassia book for stacks and queues. Programming problem 1: Implement a stack using an array.

  5. Learn Data Structures and Algorithms

    Common data structures include arrays, linked lists, stacks, queues, trees, and graphs , each serving specific purposes based on the requirements of the problem at hand. Understanding data structures is fundamental for designing efficient algorithms and optimizing software performance. Common Data Structures to learn: 1. Array. Array is a ...

  6. Assignment 1: JavaScript fundamentals

    Part 1: Warmup exercises. The first part of the assignment consists of a few short warmup exercises, designed to give you practice with JavaScript data structures. You will write your answers in warmups.js, which has already been included in index.html. We have provided a function testWarmups(), callable from the console, to check your answers.

  7. Assignment 1

    Parts of this assignment were originally written by Jeff Ondich and Anna Rafferty. Later modifications were made by Layla Oesper, Eric Alexander, and Titus Klinge. Part 1: Background and Logistics Read the course syllabus and familiarize yourself with the course schedule. Complete the background questionnaire.

  8. PDF Assignment 1 Hybrid Data Structures

    Assignment 1 Hybrid Data Structures. 15-414: Bug Catching: Automated Program Verification. Due Thursday, February 24, 2022 (checkpoint) Thursday, March 3, 2022 (final) You should pick one of the following three alternative mini-projects. You may, but are not required to, do this assignment with a partner.

  9. Data Structures

    Welcome to Data Structures, CS112. After completing the course the student will be able to: Analyze runtime efficiency of algorithms related to data structure design. Select appropriate abstract data types for use in a given application. ... Always make a copy of your assignment. Remember that technical problems happen and that due dates are ...

  10. Data Structures Assignment 1

    Assignment In this assignment you have to use both linked lists and arrays to store data about students, hostels, courses, etc. ... allCourses), updating all data structures. Student record file will contain record details of student in this order: entry number, name, department, and hostel. These names are single word strings, separated by ...

  11. DS(MCE) Assignment 1 Solutions

    Lecture notes on DSA assignment data structures (cs251) consider the linear arrays and find the number of elements in each array. suppose base 300 and words per. Skip to document. ... DATA STRUCTURES (CS251) 1. Consider the linear arrays AAA [5 : 50], BBB [- 5 : 10] and CCC [1 : 8]. a. Find the number of elements in each array.

  12. Assignment 1

    Assignment Data Structures and Algorithms for AI Computer Science Department, VU Amsterdam Please write your full name here! September 19, 2021. Instructions:This is the first assignment of the course. The assignment consists of four questions and they appear below. Your job is to answer the questions and submit your solutions in PDF format via ...

  13. Data Structures

    Data Structures. Assignments are due at 11:00PM. The due dates are strictly followed. Assignments are graded automatically by AutoLab. Your program must compile without errors on Autolab - otherwise you will not receive any credit for the assignment. For each problem, your code will be tested using a suite of test cases, and you will receive ...

  14. Assignments

    Use at least 10 pt font and 1 inch margins. This rule is meant to prepare you for writing research publications: one often has to explain great ideas in a very limited number of pages. Submissions must be made online and consist of a compiled PDF document. Grades and comments will be posted online.

  15. Data Structure

    Data Structure_Assignment 1 - Free download as PDF File (.pdf), Text File (.txt) or read online for free.

  16. Data structures and algorithms assignment 1

    Download Data structures and algorithms assignment 1 and more Data Structures and Algorithms Assignments in PDF only on Docsity! Higher Nationals in Computing Unit 19: Data Structures and Algorithms ASSIGNMENT 1 Assessor name: PHAN MINH TAM Learner's name: Pham Nguyen Hung Cuong ID: GCS210364 Class: GCS0905B Subject code: 1649 Assignment due ...

  17. 1649-Assignment 1-Data Structure

    Download 1649-Assignment 1-Data Structure and more Data Structures and Algorithms Assignments in PDF only on Docsity! Page 1 of 21 Higher Na onals in Compu ng Advanced Programming Assignment 1 Student's name: AU LAM THANH DAT ID: GCS210113 Class: GCS1003B Subject code: 1649 Assessor name: LE NGOC THANH Page 2 of 21 ASSIGNMENT 1 FRONT SHEET Qualification BTEC Level 5 HND Diploma in Computing ...

  18. CS 225

    Part 1: The PuzzleState data structure. In the first part of this assignment we will work on representing the puzzle as a graph. To do this we will have a node for every possible position of the puzzle and an edge between two nodes if there is a single move of a tile that will move from one position to the next. The tricky part in this is that ...

  19. Assignment 1

    Curse: T0504-1 Relational Databases & SQL Module 1: Foundations of Database Systems Assignment 1: Database Basics Student: Professor: 1. Describe the basic data-modeling building blocks. The basic building blocks of all data models are entities, attributes, relationships, and constraints. Entity: Could be a person, place, thing, concept, or ...