Sprint 4 DSA-JS - 101
Sprint 4 DSA-JS - 101
Session 1
Agenda
● DSA
○ What? Why? How?
● Introduction to Crio DSA Platform
● JavaScript Recap
○ Variables, Data Types, Loops, Conditional Statements
● Problem Solving
DSA
● What?
○ Combination of Data Structures and Algorithms
○ Data structure: efficient data management to improve storage and retrieval
○ Algorithm: set of instructions to solve a particular problem
● Why should you learn?
○ A building block of Software Development
○ Helps us keep our applications/softwares memory and time efficient
○ Helps shape our thought process - try to optimize our solution, suggest alternatives
○ Similar process is being followed in Software Development
○ Popular interview standard
● How?
○ Consistency is the key, practice daily!!
○ Ensure that you solve problem on your own, do not copy-paste from internet
○ Ok to read/understand the solution, but please implement it on your own after that
○ We will share a methodology (a step by step process) that can be used to solve any problem
○ Avoid procrastination and stacking up the problems for the last week
○ Discuss your ideas with mentors/TAs/peers
Introduction to the Crio DSA Platform
● Syntax
○ Each programming language has it own syntax (though there are a lot of similarity)
○ Get comfortable with the fundamentals
○ Keywords: predefined, reserved words that have special meanings to the compiler
● Data types
○ Classification of data like: String, Number, Boolean, Undefined, NULL
○ Further sub-division of data.
■ Why do you think this sub classification is required? - Better memory management
○ Data types vs data structures?
Programming Fundamentals
● Constraints
○ Refers to restrictions, limitations.
○ Generally imposed on the input, helps us figure out the correct data type and algorithm
○ Example: the array given to you will have less than 10^6 elements
● Debugging
○ Identification and removal of bugs/errors in the code
○ Important skill that comes when writing and executing code
Programming Constructs
Syntax: Example:
if (hour < 18) {
if (condition) { greeting = "Good day";
// block of code to be executed if the condition is true } else {
} else { greeting = "Good evening";
// block of code to be executed if the condition is false }
}
Recap: if else chain
Use the else if statement to specify a new condition if the first condition is false.
Syntax:
Example:
if (condition1) {
if (time < 10) {
// Block 1: block of code to be executed if condition1 is true
greeting = "Good morning";
}
}
else if (condition2) {
else if (time < 20) {
// Block 2: block of code to be executed if the condition1 is
greeting = "Good day";
false and condition2 is true
}
}
else {
else {
greeting = "Good evening";
// Block 3: block of code to be executed if the condition1 is
}
false and condition2 is false
}
Recap: Nested if else
Syntax:
Example:
if (condition1) {
if (time = 10) {
// Block 1: block of code to be executed if condition1 is true
console.log(“Good morning");
if (condition2) {
if (awake!= true) {
// Block 2: block of code to be executed if the
console.log(“WAKE UP!");
condition1 is true and condition2 is true
}
}
else {
else {
console.log(“Drink coffee");
// Block 3: block of code to be executed if the
}
condition1 is true and condition2 is false
else {
}
console.log(“Continue sleeping :)");
}
}
else {
// Block 4: block of code to be executed if the
condition1 is false
}
Activity - Find the Quadrant
Activity link
5 minute break
While Loop
Recap - For Loop false
Notice the
1 2 semicolons?
Block of code
} Exit
Break
Continue
Activity - Natural Sum
Activity link
End of session quiz
Link: https://www.crio.do/magic/introduction-end-of-session-quiz
Session 2
Agenda
Way to measure how well our algorithm scales as the amount of data increases
Time Complexity - O(n) - Linear Search, grows directly in proportion to the input data size
Space Complexity - O(1) - No size specific data structure used
Time Complexity - O(n*m) - Running 2 loops but each one iterates to a different length
Space Complexity - O(min(n, m))
Activity #3 What’s the Time complexity here?
Time Complexity - O(n + m) - Running 2 loops but they are not nested
Space Complexity - O(1) - constant number of variables
Activity #4 What’s the Time complexity here?
Time Complexity - O(n) - Linear Search, grows directly in proportion to the input data size
Space Complexity - O(1) - No size specific data structure used
Time Complexity - O(n*m) - Running 2 loops but each one iterates to a different length
Space Complexity - O(min(n, m))
Activity #3 What’s the Space complexity here?
function getBinaryArray(arr, n) {
const binaryArray = new Array(n);
return binaryArray;
}
function reverseString(str, m) {
let revStr = "";
for(let i=m-1;i>=0;i--){
revStr += str[i];
}
return revStr;
}
Example 1 - Finding the count of common elements between two arrays can be solved using
nested for loop taking n*m time but with constant space. If we use extra space to store these
elements in a Map, time complexity will be linear therefore trading off space over time.
Example 2 - Finding count of each element in array can be solved using nested for loop in n*n
time with constant space, but if we use extra space to store the count in a map then time
complexity will be linear by trading off space over time.
5 minute break
Approach to resolving errors - Debugging
● What?
○ Process where we find and fix errors/bugs in code
● Why?
○ Debugging and coding goes hand-in-hand with Software Development
○ Treat issues/errors as learning opportunity
○ Build confidence yourselves trying to debug and figuring out things by yourselves,
incrementally
○ In the later sessions, the errors you come across will need more skill to be debugged.
Walkthrough of the Debugging Template
● How ?
○ PDF Link for Flowchart (for easy access for learners) - Link
○ Types and Examples of Common Errors (for JavaScript) - Link
Activity - Find the Quadrant
Activity link
Activity - Natural Sum
Activity link
End of session quiz
Link: https://www.crio.do/magic/time-complexity-debugging-end-of-session-quiz
Session 3
Agenda
● Collections in JavaScript
● Introduction to 1D Arrays
Crio Problem Solving Methodology
For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.
Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
What are Collections?
together.
● Collections encompass various data structures or objects that allow for the storage,
● Arrays, Objects, Map, Set, and other built-in structures can be considered collections.
Key Takeaway: You don’t need to implement the Data Structures from scratch while solving problems.
Use available Collections and focus on the logic.
Arrays in JavaScript
● What?
○ Store items (generally, similar type) in contiguous memory location
○ Concept
● Why?
○ Think: How would you calculate the sum of 100 integers? Use 100 different variables? What
is the issue here?
● Index
○ Index value represent the position of an element in an array
○ Indexing starts from 0 and goes uptill (size of array - 1)
○ To visit all elements of the array, we can through the index in the range [0, size - 1]
.
● sort() tries to convert the array elements to strings first and sorts lexicographically
(dictionary order).
● Customise how sort() is done with a comparator function. The comparator functions
takes in two arguments to compare (say a and b)
○ If the function returns -ve number then that means to sort a before b
○ If the function returns a +ve number that means to sort b before a
○ If the function returns 0 then it means to keep the original ordering of a and b
nums.sort(function (a, b) {
if (a < b) return -1; // or any negative value
else if (a > b) return 1; // or any positive value
else return 0;
})
5 minute break
Activity - Find given element in the array
Activity link
Activity link
Link: https://www.crio.do/magic/arrays-end-of-session-quiz
Session 4
Agenda
● Introduction to Strings
● What?
○ Array of characters
○ Can contain alphanumeric characters, special characters
○ Lot of similarity with arrays:
■ Concept of indexing
■ Common methods like -
● slice()
● indexOf()
● includes()
● split()
● join()*
Common terminologies
● Substring vs Subsequence
○ Substring: Continuous part of string, take out characters from a string placed b/w two
indices in a continuous order
○ Subsequence: Remove zero or more characters b/w two indices, without changing the
order of the remaining elements.
○ Examples: “thequickbrownfox” - substring: “quick” - subsequence: “qck”
● Prefix vs Suffix
○ Prefix: substring that occurs at the beginning of the string
○ Suffix: substring that occurs at the end of the string
● Mutable vs Immutable
○ Strings are immutable in JavaScript
■ Mutable: object value can be changed after initialization
■ Immutable: object value cannot be changed after initialization
Common string operations
● Reversing a string
● Check if strings are identical
● Sorting
● Concatenation
● Count characters
● Removing characters
● Printing substrings/subsequences
Activity - Capitalise first letter of every word
Activity link
Activity Link
Activity link
● Additional takeaways
○ The pointers can traverse in different directions (e.g. Check for palindrome where pointers move towards
each other from either end, moving in the same direction - Check if array is sorted).
End of session quiz
Link: https://www.crio.do/magic/string-two-pointer-end-of-session-quiz
Session 5
Agenda
● Introduction to Matrix
● What?
○ 2D arrays, grid like structure
○ Think of 1D array stacked on top of each other
○ Have the concept of rows and columns
● Why?
○ Heavily used in real life, example board games
○ Used in graph, backtracking, dynamic programming problems that need a grid representation
● Traversal - visiting all elements
○ We maintain two separate coordinates
○ Row index keeps track of the row while the column index keeps track of column
● Dimension
○ Represent size of a matrix
○ row X col
● Single Row, Single Column, Square vs rectangular matrix
Visualise 1D, 2D, 3D array and so on…
Matrix traversal
Activity link
● What?
○ Searching algorithm (the other common one is Linear Search)
○ Helps find a target element in an sorted array
● Why?
○ Extremely fast searching
○ Time complexity: O(log N). (In comparison, TC for Linear Search is O(n))
● Where?
○ Can be used to find an element among billions of sorted elements
● Key Requirement for Data to apply BS
○ Data should be sorted (Ascending/Descending or Alphabetic order)
Is O(logN) a big deal? YES!
Binary Search Steps
● Step 1
○ Set the search space equal to sorted array
○ Find a target element in a sorted array
● Step 2
○ Compare the target with the middle element
○ Case 1: Target element = middle element
■ Return the index
○ Case 2: Target element < middle element
■ Discard the middle element and all the elements on the right of it
○ Case 3: Target element > middle element
■ Discard the middle element and all the elements on the left of it
● Step 3
○ If the target was not found and there is no more elements left to search, return -1
Activity - Find element using Binary Search
Activity link
Link: https://www.crio.do/magic/matrix-binary-search-end-of-session-quiz
Session 6
Agenda
● Problem Solving
Crio Problem Solving Methodology
For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.
Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
Activity - Reverse words in a String
Activity link
5 minute break
Activity - String Compress
Activity link
Take-home Walkthrough
● Problem 1
● Problem 2
● Problem 3
Thank you
While folks are joining
Session 7
Agenda
● Recursion
○ What? Why? When?
○ Real life examples
○ Is recursion better than iteration?
○ Base case
○ Recursive condition
○ Function signatures
○ Recursion template
Recursion
● What?
○ Recursion is a method where the solution to a problem depends on solutions to smaller instances of the
same problem. A method (function) can call itself in order to solve the problem.
● Real world example
○ Counting number of rows in a movie theater
○ Searching for a word in dictionary
● Why?
○ Recursive solutions are often simpler and easier to understand and implement than iterative solutions.
○ Complex real world problems can be easily represented using recursion.
○ Recursion is well-suited for processing and manipulating data structures with recursive properties, such as
linked lists, trees, and graphs.
○ Recursion encourages a recursive mindset, which is a valuable problem-solving skill applicable to various
domains. It trains the ability to break down complex tasks into simpler ones and solve them
independently.
Recursion
● When?
○ Use when the problem can be broken down into smaller, repetitive problems.
○ It is especially good for working on things that have many possible branches and are too complex
for an iterative approach.
● Is recursion better than iteration?
○ Problems that we solve using recursion can also be solved iteratively!
○ Some problems requires multiple nested loops where it is easier to implement a recursive
solution
○ However, for most of the cases, recursive solutions consume more space as compared to iterative
solutions. Why?
Recursion - Key Aspects
● Base/Terminating condition
○ The case for which the solution can be stated non‐recursively/directly/trivially.
● Recursive condition
○ The case for which the solution is expressed in terms of a smaller version of itself.
● Function signature
○ Return type
○ Input parameter
Recursion Template
Let’s try out this recursion problem
Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
Activity - Sum of first N natural numbers
Activity link
● What?
○ It’s a series where sum of nth term is equal to sum of previous 2 terms
○ F(n) = F(n-1) + F(n-2) for each n >= 2
○ F(1) =0
○ F(2) = 1
Series: 0, 1, 1, 2, 3, 5, 8, 13, 21 . . .
Activity link
Link: https://www.crio.do/magic/recursion-end-of-session-quiz
Session 8
Agenda
● Map
○ What? Why? When?
○ CRUD operations
● Activities
Map
● What?
○ Data structure that can perform fast lookups.
○ Based on the concept of key-value pair
○ Key = Unique Id
○ Value = Details for that key
○ Key and Value can be of different data types
● Properties
○ Keys CANNOT repeat, has to be unique
○ INSERT not possible if the key already exists
○ UPDATE Value for a Key
○ DELETE based on Key
○ POSITION doesn’t matter
○ SEARCH based on Keys (generally, this is more optimal) or values
○ SORT - may be sorted based on Key
● How would you do this if you don’t use a map?
Map
● CRUD operations
○ set(key, value): Adds a new key-value pair to the map or updates the value of an existing key.
○ get(key): Returns the value associated with the specified key, or undefined if the key is not found
in the map.
○ has(key): Returns a boolean indicating whether the specified key is present in the map.
○ delete(key): Removes the key-value pair associated with the specified key from the map.
○ clear(): Removes all key-value pairs from the map.
Crio Problem Solving Methodology
For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.
Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
Activity - Maximum Repeating Word
Activity link
Activity link
Link: https://www.crio.do/magic/map-end-of-session-quiz
Session 9
Agenda
● Set
○ What? Why? When?
○ CRUD operations
● Activities
Set
● What?
○ Data structure that can perform fast lookups.
○ Similar to map
○ Based only the concept of key. No values here!
○ Key = Unique Id which can be of any data type
● Properties
○ Keys CANNOT repeat, has to be unique
○ SIZE of the set is important. It tells us the count of unique keys
○ INSERT not possible if the key already exists
○ DELETE a Key
○ POSITION doesn’t matter
○ SEARCH based on Keys (generally, this is more optimal). Can take linear time
● How would you do this if you don’t use a set?
Set
● CRUD operations
○ add(value): Adds a new value to the set.
○ has(value): Returns a boolean indicating whether the specified value is present in the set.
○ delete(value): Removes the specified value from the set.
○ clear(): Removes all values from the set.
Crio Problem Solving Methodology
For any given problem, following these milestones of Crio Methodology will help you solve the problem
systematically.
Milestone 5: Prove that your code works using custom test cases
1. Make sure you check boundary conditions and other test cases you noted in Milestone 1
a. If compiler is not available, dry run your code on a whiteboard or paper
2. 2. Suggest optimizations if applicable during interviews
Activity - Find count of unique elements
Activity link
Activity link
Link: https://www.crio.do/magic/set-end-of-session-quiz
Session 10
Agenda
● Math concepts
● Debugging Problems
Prime numbers
● What?
○ A positive integer that is divisible only by 1 and itself
○ Examples: 2, 3, 5, 7, 11, 13, 17, 23 …
○ Is 1 a prime number?
● How to check for prime?
○ Can we do better than O(N) ?
Activity - Count Prime Numbers
Activity link
● What?
○ Also known as HCF (Highest Common factor)
○ Always computed for a pair
○ Largest number that can divide the pair without leaving remainder
○ Example:
■ GCD(24, 36) = 12
● How?
○ Euclidean algorithm
Activity link
● What?
○ Pair whose only common factor is 1
■ isCoprime(8, 9) = true
● How?
○ Since 1 is the only common factor, we can also say the highest common factor is 1
○ For a pair to be co prime, their GCD should be 1
5 minute break
Debugging Activity - Reverse Number
Activity link
Debugging Activity - Nth Fibonacci Number
Activity link
Debugging Activity - Unique String
Activity link
Thank you