Gunjan  Khaitan

Gunjan Khaitan

1632359850

Data Structures And Algorithms Full Course

This video on Data Structures and Algorithms Full Course will help you learn everything there is to master Data Structures and Different Algorithms. This Data Structure full Course will cover everything from what is an algorithm, arrays, linked list, stacks, queues to different algorithms. The following topics are covered in this Data Structure and Algorithms Full Course.

Introduction to Data Structures?
A data structure is a collection of data pieces that provides an efficient method for storing and organising data in a computer so that it may be used effectively. Arrays, Linked Lists, Stacks, Queues, and other Data Structures are examples. Data Structures are employed in practically every element of computer science, including operating systems, compiler design, artificial intelligence, graphics, and many more applications.

What Is a Data Structure?
The short answer is: a data structure is a specific means of organizing data in a system to access and use. The long answer is a data structure is a blend of data organization, management, retrieval, and storage, brought together into one format that allows efficient access and modification. It’s collecting data values, the relationships they share, and the applicable functions or operations.

Why Is Data Structure Important?
The digital world processes an increasing amount of data every year. According to Forbes, there are 2.5 quintillion bytes of data generated daily. The world created over 90 percent of the existing data in 2018 in the previous two years! The Internet of Things (IoT) is responsible for a significant part of this data explosion. Data structures are necessary to manage the massive amounts of generated data and a critical factor in boosting algorithm efficiency. Finally, since nearly all software applications use data structures and algorithms, your education path needs to include learning data structure and algorithms if you want a career as a data scientist or programmer. Interviewers want qualified candidates who understand how to use data structures and algorithms, so the more you know about the concepts, the more comfortably and confidently you will answer data structure interview questions.

#datastructures #algorithms

 

Data Structures And Algorithms Full Course
Beth  Nabimanya

Beth Nabimanya

1631173210

Learn About Cheat Sheet in Data Structure

This article contains the worse case time complexity of a vast number of operations with various data structures.

#datastructures 

Learn About Cheat Sheet in Data Structure
Code  Camp

Code Camp

1631112112

Data Structures and Algorithms in Python - Full Course for Beginners

A beginner-friendly introduction to common data structures (linked lists, stacks, queues, graphs) and algorithms (search, sorting, recursion, dynamic programming) in Python. This course will help you prepare for coding interviews and assessments.

⭐️ Course Contents ⭐️
⌨️ (00:00:11) Introduction
⌨️ (00:01:43) Binary Search Linked Lists and Complexity
⌨️ (00:03:43) Introduction
⌨️ (00:08:35) Problem
⌨️ (00:12:17) The Method
⌨️ (00:13:55) Solution
⌨️ (00:50:52) Complexity and Big O notation
⌨️ (01:24:57) Binary Search vs Linear Search
⌨️ (01:31:40) Generic Binary Search
⌨️ (01:40:08) Summary and Conclusion
⌨️ (01:44:30) Assignment Walkthrough
⌨️ (01:45:05) Introduction
⌨️ (01:50:01) Problem- Rotated Lists
⌨️ (01:53:02) The Method
⌨️ (01:54:03) Solution
⌨️ (02:30:47) Summary and Conclusion
⌨️ (02:33:29) Binary Search Trees Python Tutorial
⌨️ (02:34:41) Introduction
⌨️ (02:37:36) Problem
⌨️ (02:38:40) The Method
⌨️ (03:13:58) Binary tree
⌨️ (03:27:16) Traversing Binary Tree
⌨️ (03:36:10) Binary Search Tree
⌨️ (04:22:37) Self-Balancing Binary Trees and AVL Trees
⌨️ (04:26:27) Summary and Conclusion
⌨️ (04:30:33) Hash Tables and Python Dictionaries
⌨️ (04:31:09) Introduction
⌨️ (04:34:00) Problem
⌨️ (04:40:28) Data List
⌨️ (04:42:52) Hash Function
⌨️ (04:54:52) Basic Hash Table Implementation
⌨️ (05:03:07) Handling Collisions with Linear Probing
⌨️ (05:09:24) Summary and Conclusion
⌨️ (05:16:47) Sorting Algorithms and Divide & Conquer
⌨️ (05:17:48) Introduction
⌨️ (05:20:19) Problem
⌨️ (05:21:27) The Method
⌨️ (06:40:49) Custom Comparison Functions
⌨️ (06:48:53) Summary and Conclusion
⌨️ (06:54:57) Recursion Memoization & Dynamic Programming
⌨️ (06:56:37) Introduction
⌨️ (07:00:04) Problem
⌨️ (07:04:28) The Method
⌨️ (07:06:21) Solution
⌨️ (08:06:13) Knapsack Problems
⌨️ (08:08:48) The Method
⌨️ (08:09:24) Solution
⌨️ (08:43:26) Summary and Conclusion
⌨️ (08:44:05) Graph Algorithms BFS, DFS & Shortest Paths
⌨️ (08:45:02) Introduction
⌨️ (08:51:00) Graph Data Structure
⌨️ (09:15:57) Graph Algorithms - Breadth-First Search
⌨️ (09:37:28) Depth-First Search
⌨️ (10:08:26) Shortest Paths
⌨️ (10:40:39) Summary and Conclusion
⌨️ (10:42:21) Python Interview Questions Tips & Advice
⌨️ (10:43:09) Introduction
⌨️ (10:44:08) The Method
⌨️ (10:47:10) Solution
⌨️ (12:30:51) Summary and Conclusion

⭐️ Course Lessons with Code ⭐️
🟢 Lesson 1 - Binary Search, Linked Lists and Complexity
  💻 Linear and Binary Search: https://jovian.ai/aakashns/python-binary-search 
  💻 Problem Solving Template: https://jovian.ai/aakashns/python-problem-solving-template 
  💻 Linked Lists in Python: https://jovian.ai/aakashns/python-classes-and-linked-lists 
🟢 Assignment 1 - Binary Search Practice
  💻 Starter Notebook: https://jovian.ai/aakashns/python-binary-search-assignment 
🟢 Lesson 2 - Binary Search Trees, Traversals and Recursion
  💻 Binary Search Trees in Python: https://jovian.ai/aakashns/python-binary-search-trees 
  💻 Problem Solving Template: https://jovian.ai/aakashns/python-problem-solving-template 
  💻 Linked Lists in Python: https://jovian.ai/aakashns/python-classes-and-linked-lists 
🟢 Assignment 2 - Hash Tables and Python Dictionaries
  💻 Starter Notebook: https://jovian.ai/aakashns/python-hash-tables-assignment 
🟢 Lesson 3 - Sorting Algorithms and Divide & Conquer
  💻 Sorting and Divide & Conquer: https://jovian.ai/aakashns/python-sorting-divide-and-conquer 
  💻 Problem Solving Template: https://jovian.ai/aakashns/python-problem-solving-template 
🟢 Assignment 3 - Divide and Conquer Practice
  💻 Starter Notebook: https://jovian.ai/aakashns/python-divide-and-conquer-assignment 
🟢 Lesson 4 - Recursion and Dynamic Programming
  💻 Problem-solving template: https://jovian.ai/aakashns/python-problem-solving-template 
  💻 Dynamic Programming problems: https://jovian.ai/aakashns/dynamic-programming-problems 
🟢 Lesson 5 - Graph Algorithms (BFS, DFS & Shortest Paths)
  💻 Graphs and Graph Algorithms (Starter Notebook): https://jovian.ai/aakashns/python-graph-algorithms 
🟢 Project - Step-by-Step Solution to a Programming Problem
  💻 Starter Notebook: https://jovian.ai/aakashns/python-problem-solving-template 
🟢 Lesson 6 - Python Interview Questions, Tips & Advice
  💻 Problem solving template: https://jovian.ai/aakashns/python-problem-solving-template 
  💻 Coding problem 1: https://jovian.ai/aakashns/python-subarray-with-given-sum 
  💻 Coding problem 2: https://jovian.ai/aakashns/python-minimum-edit-distance 

🔗 Course website: https://jovian.ai/learn/data-structures-and-algorithms-in-python

#python #datastructures #algorithms

Data Structures and Algorithms in Python - Full Course for Beginners
Fleta  Dickens

Fleta Dickens

1630836000

Learn About The Basic Functionality Of Stack Data Structures.

This video goes over the basic functionality of the stack data structure.

Code: https://pastebin.com/92NGniRU

Sections:
0:00 Introduction
0:20 What are Stacks?
2:21 Code Example

#datastructures 

Learn About The Basic Functionality Of Stack Data Structures.
Code  Camp

Code Camp

1629816409

How to Create an Android App with Kotlin and Jetpack Compose UI

Create an Android app with Kotlin and Jetpack Compose UI. Learn about Graph data structures and algorithms by building a Sudoku app.

Timestamps:
⌨️ (0:00:16) Introduction & Overview: Topics, Source
⌨️ (0:02:39) App Design Approach: 3rd Party Library Minimalism & MV-Whatever Architecture
⌨️ (0:04:50) Domain package: Repository Pattern, Enum, Data Class, Sealed Class, Hash Code, Interfaces
⌨️ (0:34:39) Common package: Extension Functions & Variables, Open-Closed Principle (OCP), Abstract Class, Singleton
⌨️ (0:50:20) Persistence (Storage) package: Clean Architecture Back End w/ Java File System Storage, Jetpack Proto Datastore
⌨️ (1:28:07) UI package: Jetpack Compose UI Basics, Styles, Typography,  Light & Dark Themes
⌨️ (1:39:56) UI Components package: Modifiers, Reusable Toolbar & Loading Screens
⌨️ (1:52:08) UI Active Game Feature package: Presentation Logic & ViewModel w/ Coroutines, Kotlin Function Types
⌨️ (2:30:55) UI Active Game Feature package: Sudoku Game with Jetpack Compose UI & Activity Container
Note: In a larger App, I'd suggest using Fragments as Containers; didn't make sense to with this app though
⌨️ (3:15:58) Computation Logic package:  Overview, design, and testing of Graph DS & Algos for n-sized *square* Sudokus

💻 Full Source Code Here:: https://github.com/BracketCove/GraphSudokuOpen/tree/master/app/src/main/java/com/bracketcove/graphsudoku 
💻 Starting Point Branch Here: https://github.com/BracketCove/GraphSudokuOpen/tree/starting_point 

#kotlin #android #jetpack #datastructures #algorithms

How to Create an Android App with Kotlin and Jetpack Compose UI
Dylan  Iqbal

Dylan Iqbal

1629429900

JavaScript Algorithms and Data Structures: Everything You Need to Know

This repository contains JavaScript based examples of many popular algorithms and data structures.

Each algorithm and data structure has its own separate README with related explanations and links for further reading (including ones to YouTube videos).

☝ Note that this project is meant to be used for learning and researching purposes only, and it is not meant to be used for production.

Data Structures

A data structure is a particular way of organizing and storing data in a computer so that it can be accessed and modified efficiently. More precisely, a data structure is a collection of data values, the relationships among them, and the functions or operations that can be applied to the data.

B - Beginner, A - Advanced

Algorithms

An algorithm is an unambiguous specification of how to solve a class of problems. It is a set of rules that precisely define a sequence of operations.

B - Beginner, A - Advanced

Algorithms by Topic

Algorithms by Paradigm

An algorithmic paradigm is a generic method or approach which underlies the design of a class of algorithms. It is an abstraction higher than the notion of an algorithm, just as an algorithm is an abstraction higher than a computer program.

How to use this repository

Install all dependencies

npm install

Run ESLint

You may want to run it to check code quality.

npm run lint

Run all tests

npm test

Run tests by name

npm test -- 'LinkedList'

Troubleshooting

In case if linting or testing is failing try to delete the node_modules folder and re-install npm packages:

rm -rf ./node_modules
npm i

Playground

You may play with data-structures and algorithms in ./src/playground/playground.js file and write tests for it in ./src/playground/__test__/playground.test.js.

Then just simply run the following command to test if your playground code works as expected:

npm test -- 'playground'

Useful Information

References

▶ Data Structures and Algorithms on YouTube

Big O Notation

Big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows. On the chart below you may find most common orders of growth of algorithms specified in Big O notation.

Big O graphs

Source: Big O Cheat Sheet.

Below is the list of some of the most used Big O notations and their performance comparisons against different sizes of the input data.

Big O NotationComputations for 10 elementsComputations for 100 elementsComputations for 1000 elements
O(1)111
O(log N)369
O(N)101001000
O(N log N)306009000
O(N^2)100100001000000
O(2^N)10241.26e+291.07e+301
O(N!)36288009.3e+1574.02e+2567

Data Structure Operations Complexity

Data StructureAccessSearchInsertionDeletionComments
Array1nnn 
Stacknn11 
Queuenn11 
Linked Listnn1n 
Hash Table-nnnIn case of perfect hash function costs would be O(1)
Binary Search TreennnnIn case of balanced tree costs would be O(log(n))
B-Treelog(n)log(n)log(n)log(n) 
Red-Black Treelog(n)log(n)log(n)log(n) 
AVL Treelog(n)log(n)log(n)log(n) 
Bloom Filter-11-False positives are possible while searching

Array Sorting Algorithms Complexity

NameBestAverageWorstMemoryStableComments
Bubble sortnn2n21Yes 
Insertion sortnn2n21Yes 
Selection sortn2n2n21No 
Heap sortn log(n)n log(n)n log(n)1No 
Merge sortn log(n)n log(n)n log(n)nYes 
Quick sortn log(n)n log(n)n2log(n)NoQuicksort is usually done in-place with O(log(n)) stack space
Shell sortn log(n)depends on gap sequencen (log(n))21No 
Counting sortn + rn + rn + rn + rYesr - biggest number in array
Radix sortn * kn * kn * kn + kYesk - length of longest key

Read this in other languages: 简体中文, 繁體中文, 한국어, 日本語, Polski, Français, Español, Português, Русский, Türk, Italiana, Bahasa Indonesia, Українська, Arabic, Deutsch

Download Details:

Author: trekhleb
Official Website: https://github.com/trekhleb/javascript-algorithms
License: MIT

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Everything You Need to Know
Dylan  Iqbal

Dylan Iqbal

1629415440

JavaScript Algorithms and Data Structures: Combination Sum

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

The same repeated number may be chosen from candidates unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Examples

Input: candidates = [2,3,6,7], target = 7,

A solution set is:
[
  [7],
  [2,2,3]
]
Input: candidates = [2,3,5], target = 8,

A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

Explanations

Since the problem is to get all the possible results, not the best or the number of result, thus we don’t need to consider DP (dynamic programming), backtracking approach using recursion is needed to handle it.

Here is an example of decision tree for the situation when candidates = [2, 3] and target = 6:

                0
              /   \
           +2      +3
          /   \      \
       +2       +3    +3
      /  \     /  \     \
    +2    ✘   ✘   ✘     ✓
   /  \
  ✓    ✘    

References

The Original Article can be found on https://github.com

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Combination Sum
Dylan  Iqbal

Dylan Iqbal

1629411780

JavaScript Algorithms and Data Structures: Knight's Tour

A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. If the knight ends on a square that is one knight's move from the beginning square (so that it could tour the board again immediately, following the same path), the tour is closed, otherwise it is open.

The knight's tour problem is the mathematical problem of finding a knight's tour. Creating a program to find a knight's tour is a common problem given to computer science students. Variations of the knight's tour problem involve chessboards of different sizes than the usual 8×8, as well as irregular (non-rectangular) boards.

The knight's tour problem is an instance of the more general Hamiltonian path problem in graph theory. The problem of finding a closed knight's tour is similarly an instance of the Hamiltonian cycle problem.

Knight's Tour

An open knight's tour of a chessboard.

Knight's Tour

An animation of an open knight's tour on a 5 by 5 board.

References

The Original Article can be found on https://github.com

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Knight's Tour
Dylan  Iqbal

Dylan Iqbal

1629408060

JavaScript Algorithms and Data Structures: N-Queens Problem

The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general n queens problem of placing n non-attacking queens on an n×n chessboard, for which solutions exist for all natural numbers n with the exception of n=2 and n=3.

For example, following is a solution for 4 Queen problem.

N Queens

The expected output is a binary matrix which has 1s for the blocks where queens are placed. For example following is the output matrix for above 4 queen solution.

{ 0,  1,  0,  0}
{ 0,  0,  0,  1}
{ 1,  0,  0,  0}
{ 0,  0,  1,  0}

Naive Algorithm

Generate all possible configurations of queens on board and print a configuration that satisfies the given constraints.

while there are untried configurations
{
   generate the next configuration
   if queens don't attack in this configuration then
   {
      print this configuration;
   }
}

Backtracking Algorithm

The idea is to place queens one by one in different columns, starting from the leftmost column. When we place a queen in a column, we check for clashes with already placed queens. In the current column, if we find a row for which there is no clash, we mark this row and column as part of the solution. If we do not find such a row due to clashes then we backtrack and return false.

1) Start in the leftmost column
2) If all queens are placed
    return true
3) Try all rows in the current column.  Do following for every tried row.
    a) If the queen can be placed safely in this row then mark this [row, 
        column] as part of the solution and recursively check if placing  
        queen here leads to a solution.
    b) If placing queen in [row, column] leads to a solution then return 
        true.
    c) If placing queen doesn't lead to a solution then umark this [row, 
        column] (Backtrack) and go to step (a) to try other rows.
3) If all rows have been tried and nothing worked, return false to trigger 
    backtracking.

Bitwise Solution

Bitwise algorithm basically approaches the problem like this:

  • Queens can attack diagonally, vertically, or horizontally. As a result, there can only be one queen in each row, one in each column, and at most one on each diagonal.
  • Since we know there can only one queen per row, we will start at the first row, place a queen, then move to the second row, place a second queen, and so on until either a) we reach a valid solution or b) we reach a dead end (ie. we can't place a queen such that it is "safe" from the other queens).
  • Since we are only placing one queen per row, we don't need to worry about horizontal attacks, since no queen will ever be on the same row as another queen.
  • That means we only need to check three things before placing a queen on a certain square: 1) The square's column doesn't have any other queens on it, 2) the square's left diagonal doesn't have any other queens on it, and 3) the square's right diagonal doesn't have any other queens on it.
  • If we ever reach a point where there is nowhere safe to place a queen, we can give up on our current attempt and immediately test out the next possibility.

First let's talk about the recursive function. You'll notice that it accepts 3 parameters: leftDiagonal, column, and rightDiagonal. Each of these is technically an integer, but the algorithm takes advantage of the fact that an integer is represented by a sequence of bits. So, think of each of these parameters as a sequence of N bits.

Each bit in each of the parameters represents whether the corresponding location on the current row is "available".

For example:

  • For N=4, column having a value of 0010 would mean that the 3rd column is already occupied by a queen.
  • For N=8, ld having a value of 00011000 at row 5 would mean that the top-left-to-bottom-right diagonals that pass through columns 4 and 5 of that row are already occupied by queens.

Below is a visual aid for leftDiagonal, column, and rightDiagonal.

References

The Original Article can be found on https://github.com

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: N-Queens Problem
Dylan  Iqbal

Dylan Iqbal

1629400560

JavaScript Algorithms and Data Structures: Hamiltonian Cycle

Hamiltonian path (or traceable path) is a path in an undirected or directed graph that visits each vertex exactly once. A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian path that is a cycle. Determining whether such paths and cycles exist in graphs is the Hamiltonian path problem.

Hamiltonian cycle

One possible Hamiltonian cycle through every vertex of a dodecahedron is shown in red – like all platonic solids, the dodecahedron is Hamiltonian.

Naive Algorithm

Generate all possible configurations of vertices and print a configuration that satisfies the given constraints. There will be n! (n factorial) configurations.

while there are untried configurations
{
   generate the next configuration
   if ( there are edges between two consecutive vertices of this
      configuration and there is an edge from the last vertex to 
      the first ).
   {
      print this configuration;
      break;
   }
}

Backtracking Algorithm

Create an empty path array and add vertex 0 to it. Add other vertices, starting from the vertex 1. Before adding a vertex, check for whether it is adjacent to the previously added vertex and not already added. If we find such a vertex, we add the vertex as part of the solution. If we do not find a vertex then we return false.

References

The Original Article can be found on https://github.com

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Hamiltonian Cycle
Dylan  Iqbal

Dylan Iqbal

1629396840

JavaScript Algorithms and Data Structures: Backtracking - Power Set

Power set of a set S is the set of all of the subsets of S, including the empty set and S itself. Power set of set S is denoted as P(S).

For example for {x, y, z}, the subsets are:

{
  {}, // (also denoted empty set ∅ or the null set)
  {x},
  {y},
  {z},
  {x, y},
  {x, z},
  {y, z},
  {x, y, z}
}

Power Set

Here is how we may illustrate the elements of the power set of the set {x, y, z} ordered with respect to inclusion:

Number of Subsets

If S is a finite set with |S| = n elements, then the number of subsets of S is |P(S)| = 2^n. This fact, which is the motivation for the notation 2^S, may be demonstrated simply as follows:

First, order the elements of S in any manner. We write any subset of S in the format {γ1, γ2, ..., γn} where γi , 1 ≤ i ≤ n, can take the value of 0 or 1. If γi = 1, the i-th element of S is in the subset; otherwise, the i-th element is not in the subset. Clearly the number of distinct subsets that can be constructed this way is 2^n as γi ∈ {0, 1}.

Algorithms

Bitwise Solution

Each number in binary representation in a range from 0 to 2^n does exactly what we need: it shows by its bits (0 or 1) whether to include related element from the set or not. For example, for the set {1, 2, 3} the binary number of 0b010 would mean that we need to include only 2 to the current set.

 abcSubset
0000{}
1001{c}
2010{b}
3011{c, b}
4100{a}
5101{a, c}
6110{a, b}
7111{a, b, c}

See bwPowerSet.js file for bitwise solution.

Backtracking Solution

In backtracking approach we're constantly trying to add next element of the set to the subset, memorizing it and then removing it and try the same with the next element.

See btPowerSet.js file for backtracking solution.

References

The Original Article can be found on https://github.com/

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Backtracking - Power Set
Dylan  Iqbal

Dylan Iqbal

1629393180

JavaScript Algorithms and Data Structures: Backtracking - Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

Unique Paths

Examples

Example #1

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Example #2

Input: m = 7, n = 3
Output: 28

Algorithms

Backtracking

First thought that might came to mind is that we need to build a decision tree where D means moving down and R means moving right. For example in case of boars width = 3 and height = 2 we will have the following decision tree:

                START
                /   \
               D     R
             /     /   \
           R      D      R
         /      /         \
        R      R            D

       END    END          END

We can see three unique branches here that is the answer to our problem.

Time Complexity: O(2 ^ n) - roughly in worst case with square board of size n.

Auxiliary Space Complexity: O(m + n) - since we need to store current path with positions.

Dynamic Programming

Let's treat BOARD[i][j] as our sub-problem.

Since we have restriction of moving only to the right and down we might say that number of unique paths to the current cell is a sum of numbers of unique paths to the cell above the current one and to the cell to the left of current one.

BOARD[i][j] = BOARD[i - 1][j] + BOARD[i][j - 1]; // since we can only move down or right.

Base cases are:

BOARD[0][any] = 1; // only one way to reach any top slot.
BOARD[any][0] = 1; // only one way to reach any slot in the leftmost column.

For the board 3 x 2 our dynamic programming matrix will look like:

 011
0011
1123

Each cell contains the number of unique paths to it. We need the bottom right one with number 3.

Time Complexity: O(m * n) - since we're going through each cell of the DP matrix.

Auxiliary Space Complexity: O(m * n) - since we need to have DP matrix.

Pascal's Triangle Based

This question is actually another form of Pascal Triangle.

The corner of this rectangle is at m + n - 2 line, and at min(m, n) - 1 position of the Pascal's Triangle.

References

The Original Article can be found on https://github.com

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Backtracking - Unique Paths
Dylan  Iqbal

Dylan Iqbal

1629389460

JavaScript Algorithms and Data Structures: Backtracking - Jump Game

The Problem

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

Example #1

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example #2

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

Naming

We call a position in the array a "good index" if starting at that position, we can reach the last index. Otherwise, that index is called a "bad index". The problem then reduces to whether or not index 0 is a "good index".

Solutions

Approach 1: Backtracking

This is the inefficient solution where we try every single jump pattern that takes us from the first position to the last. We start from the first position and jump to every index that is reachable. We repeat the process until last index is reached. When stuck, backtrack.

See backtrackingJumpGame.js file

Time complexity:: O(2^n). There are 2n (upper bound) ways of jumping from the first position to the last, where n is the length of array nums.

Auxiliary Space Complexity: O(n). Recursion requires additional memory for the stack frames.

Approach 2: Dynamic Programming Top-down

Top-down Dynamic Programming can be thought of as optimized backtracking. It relies on the observation that once we determine that a certain index is good / bad, this result will never change. This means that we can store the result and not need to recompute it every time.

Therefore, for each position in the array, we remember whether the index is good or bad. Let's call this array memo and let its values be either one of: GOOD, BAD, UNKNOWN. This technique is called memoization.

See dpTopDownJumpGame.js file

Time complexity:: O(n^2). For every element in the array, say i, we are looking at the next nums[i] elements to its right aiming to find a GOOD index. nums[i] can be at most n, where n is the length of array nums.

Auxiliary Space Complexity: O(2 * n) = O(n). First n originates from recursion. Second n comes from the usage of the memo table.

Approach 3: Dynamic Programming Bottom-up

Top-down to bottom-up conversion is done by eliminating recursion. In practice, this achieves better performance as we no longer have the method stack overhead and might even benefit from some caching. More importantly, this step opens up possibilities for future optimization. The recursion is usually eliminated by trying to reverse the order of the steps from the top-down approach.

The observation to make here is that we only ever jump to the right. This means that if we start from the right of the array, every time we will query a position to our right, that position has already be determined as being GOOD or BAD. This means we don't need to recurse anymore, as we will always hit the memo table.

See dpBottomUpJumpGame.js file

Time complexity:: O(n^2). For every element in the array, say i, we are looking at the next nums[i] elements to its right aiming to find a GOOD index. nums[i] can be at most n, where n is the length of array nums.

Auxiliary Space Complexity: O(n). This comes from the usage of the memo table.

Approach 4: Greedy

Once we have our code in the bottom-up state, we can make one final, important observation. From a given position, when we try to see if we can jump to a GOOD position, we only ever use one - the first one. In other words, the left-most one. If we keep track of this left-most GOOD position as a separate variable, we can avoid searching for it in the array. Not only that, but we can stop using the array altogether.

See greedyJumpGame.js file

Time complexity:: O(n). We are doing a single pass through the nums array, hence n steps, where n is the length of array nums.

Auxiliary Space Complexity: O(1). We are not using any extra memory.

References

The Original Article can be found on https://github.com

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Backtracking - Jump Game
Dylan  Iqbal

Dylan Iqbal

1629385740

JavaScript Algorithms and Data Structures: Regular Expression Matching

Given an input string s and a pattern p, implement regular expression matching with support for . and *.

  • . Matches any single character.
  • * Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

Note

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Examples

Example #1

Input:

s = 'aa'
p = 'a'

Output: false

Explanation: a does not match the entire string aa.

Example #2

Input:

s = 'aa'
p = 'a*'

Output: true

Explanation: * means zero or more of the preceding element, a. Therefore, by repeating a once, it becomes aa.

Example #3

Input:

s = 'ab'
p = '.*'

Output: true

Explanation: .* means "zero or more (*) of any character (.)".

Example #4

Input:

s = 'aab'
p = 'c*a*b'

Output: true

Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches aab.

References

The Original Article can be found on https://github.com

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Regular Expression Matching
Dylan  Iqbal

Dylan Iqbal

1629382020

JavaScript Algorithms and Data Structures: Floyd-Warshall Algorithm

In computer science, the Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles). A single execution of the algorithm will find the lengths (summed weights) of shortest paths between all pairs of vertices. Although it does not return details of the paths themselves, it is possible to reconstruct the paths with simple modifications to the algorithm.

Algorithm

The Floyd–Warshall algorithm compares all possible paths through the graph between each pair of vertices. It is able to do this with O(|V|^3) comparisons in a graph. This is remarkable considering that there may be up to |V|^2 edges in the graph, and every combination of edges is tested. It does so by incrementally improving an estimate on the shortest path between two vertices, until the estimate is optimal.

Consider a graph G with vertices V numbered 1 through N. Further consider a function shortestPath(i, j, k) that returns the shortest possible path from i to j using vertices only from the set {1, 2, ..., k} as intermediate points along the way. Now, given this function, our goal is to find the shortest path from each i to each j using only vertices in {1, 2, ..., N}.

Recursive Formula

Recursive FormulaRecursive Formula

This formula is the heart of the Floyd–Warshall algorithm.

Example

The algorithm above is executed on the graph on the left below:

Example

In the tables below i is row numbers and j is column numbers.

k = 0

 1234
10−2
2403
302
4−10

k = 1

 1234
10−2
2402
302
40

k = 2

 1234
10−2
2402
302
43−110

k = 3

 1234
10−20
24024
302
43−110

k = 4

 1234
10−1−20
24024
35102
43−110

References

The Original Article can be found on https://github.com

#javascript #algorithms #datastructures

JavaScript Algorithms and Data Structures: Floyd-Warshall Algorithm