easy, medium, hard question Practices
------------------------------------------------//Easy problems \\--------------------------------------------------------
//This is an anagram solution*
/* JS01/easy at main · luciferdk/JS01 (github.com) //code in github
Write a function `isAnagram` which takes 2 parameters and returns true/false if those are anagrams or not.
What's Anagram?
- A word, phrase, or name formed by rearranging the letters of another, such as spar, formed from rasp.
*/
// check this is anagram or not program
function isAnagram(str1, str2) {
// Handle whitespace, casing, and special characters:
1. Whitespace:
/\s+/g: This is a regular expression that matches one or more whitespace characters (\s+)..replace(): This method replaces all occurrences of the matched pattern (whitespace in this case) with an empty string ("").
2. Casing:
.toLowerCase(): This method converts all characters in the string to lowercase.
str1 = str1.replace(/\s+/g, "").toLowerCase();
str2 = str2.replace(/\s+/g, "").toLowerCase();
// Early return for length mismatch:
if (str1.length !== str2.length) {
return false;
}
// Use a single hashmap for efficient character counting:
const charCount = {};
for (const char of str1) {
charCount[char] = (charCount[char] || 0) + 1;
}
for (const char of str2) {
if (!charCount[char] || charCount[char] === 0) {
return false;
}
charCount[char]--;
}
// Check if all character counts have been reduced to zero:
for (const count of Object.values(charCount)) {
if (count !== 0) {
return false;
}
}
return true;
}
module.exports = isAnagram;
Explain character count how many same characters we have. code:-
----------------------------//Next\\---------------------------------
//expenditure analysis salutation*
function calculateTotalSpentByCategory(transactions) {
const categoryTotals = [];
// Iterate through each transaction
for (const transaction of transactions) {
const category = transaction.category;
// Find the existing category object in the results array
const existingCategory = categoryTotals.find(
(item) => item.category === category
);
// If the category exists, update the total spent
if (existingCategory) {
existingCategory.totalSpent += transaction.price;
} else {
// If the category doesn't exist, create a new object and add it to the results
categoryTotals.push({ category, totalSpent: transaction.price });
}
}
// Return the final array of category totals
return categoryTotals;
// return [];
const categoryTotals = [];
// Iterate through each transaction
for (const transaction of transactions) {
const category = transaction.category;
// Find the existing category object in the results array
const existingCategory = categoryTotals.find(
(item) => item.category === category
);
// If the category exists, update the total spent
if (existingCategory) {
existingCategory.totalSpent += transaction.price;
} else {
// If the category doesn't exist, create a new object and add it to the results
categoryTotals.push({ category, totalSpent: transaction.price });
}
}
// Return the final array of category totals
return categoryTotals;
// return [];
}
Absolutely, let's break down the code step by step.
**Function Declaration**
```javascript
function calculateTotalSpentByCategory(transactions) {
```
* This line defines a function named `calculateTotalSpentByCategory`.
* This function expects an input parameter called `transactions`, which is anticipated to be an array of transaction objects.
**Initialization**
```javascript
const categoryTotals = [];
```
* This line initializes an empty array named `categoryTotals`. This array will be used to store the calculated totals for each category.
**Iterating through Transactions**
```javascript
for (const transaction of transactions) {
```
* This line uses a `for...of` loop to iterate over each `transaction` object within the `transactions` array.
**Accessing Category**
```javascript
const category = transaction.category;
```
* Inside the loop, this line extracts the `category` property from the current `transaction` object.
**Finding Existing Category**
```javascript
const existingCategory = categoryTotals.find(
(item) => item.category === category
);
```
* The `.find()` method is used to search for an existing category object within the `categoryTotals` array.
* The provided callback function `(item) => item.category === category` checks if the `category` property of an `item` in the array matches the current `category`.
**Updating or Creating Category Total**
```javascript
if (existingCategory) {
existingCategory.totalSpent += transaction.price;
} else {
categoryTotals.push({ category, totalSpent: transaction.price });
}
```
* **If an existing category is found:**
- It increments the `totalSpent` property of the `existingCategory` object by the `price` of the current transaction.
* **If an existing category is not found:**
- A new object containing the `category` and initial `totalSpent` (equal to the transaction's price) is created and pushed into the `categoryTotals` array.
**Returning Results**
```javascript
return categoryTotals;
```
* Once the loop is complete, the function returns the `categoryTotals` array. This array now contains objects representing each unique category along with their corresponding total spent.
**Let me know if you would like an example to illustrate how this function works!**
**Function Declaration**
```javascript
function calculateTotalSpentByCategory(transactions) {
```
* This line defines a function named `calculateTotalSpentByCategory`.
* This function expects an input parameter called `transactions`, which is anticipated to be an array of transaction objects.
**Initialization**
```javascript
const categoryTotals = [];
```
* This line initializes an empty array named `categoryTotals`. This array will be used to store the calculated totals for each category.
**Iterating through Transactions**
```javascript
for (const transaction of transactions) {
```
* This line uses a `for...of` loop to iterate over each `transaction` object within the `transactions` array.
**Accessing Category**
```javascript
const category = transaction.category;
```
* Inside the loop, this line extracts the `category` property from the current `transaction` object.
**Finding Existing Category**
```javascript
const existingCategory = categoryTotals.find(
(item) => item.category === category
);
```
* The `.find()` method is used to search for an existing category object within the `categoryTotals` array.
* The provided callback function `(item) => item.category === category` checks if the `category` property of an `item` in the array matches the current `category`.
**Updating or Creating Category Total**
```javascript
if (existingCategory) {
existingCategory.totalSpent += transaction.price;
} else {
categoryTotals.push({ category, totalSpent: transaction.price });
}
```
* **If an existing category is found:**
- It increments the `totalSpent` property of the `existingCategory` object by the `price` of the current transaction.
* **If an existing category is not found:**
- A new object containing the `category` and initial `totalSpent` (equal to the transaction's price) is created and pushed into the `categoryTotals` array.
**Returning Results**
```javascript
return categoryTotals;
```
* Once the loop is complete, the function returns the `categoryTotals` array. This array now contains objects representing each unique category along with their corresponding total spent.
**Let me know if you would like an example to illustrate how this function works!**
------------------------------------------------//Medium Problem \\----------------------------------------------------
//palindrome solution*
function isPalindrome(str) {
// Normalize the input string:
str1 = str.toLowerCase().replace(/[^a-z0-9]/gi, '');
// Compare characters from both ends:
let left = 0;
let right = str1.length - 1;
while (left < right) {
if (str1[left] !== str1[right]) {
return false; // Not a palindrome
}
left++;
right--;
}
return true; // It's a palindrome!
}
// Normalize the input string:
str1 = str.toLowerCase().replace(/[^a-z0-9]/gi, '');
// Compare characters from both ends:
let left = 0;
let right = str1.length - 1;
while (left < right) {
if (str1[left] !== str1[right]) {
return false; // Not a palindrome
}
left++;
right--;
}
return true; // It's a palindrome!
}
Absolutely, let's break down how this JavaScript code snippet determines if a given string is a palindrome.
**What is a palindrome?**
A palindrome is a word, phrase, or sequence that reads the same backward as forward. Examples include "racecar", "madam", or "level".
**Explanation of the code:**
**1. Function Declaration**
```javascript
function isPalindrome(str) {
// ...
}
```
* This defines a function called `isPalindrome`, which takes a single input parameter `str` (the string to be checked).
**2. Input Normalization**
```javascript
str1 = str.toLowerCase().replace(/[^a-z0-9]/gi, '');
```
* **`toLowerCase()`:** Converts the input string to lowercase for case-insensitive comparison.
* **`replace(/[^a-z0-9]/gi, '')`:** This regular expression removes all non-alphanumeric characters (letters and numbers) from the string. This ensures we only compare essential characters.
**3. Two-Pointer Comparison**
```javascript
let left = 0;
let right = str1.length - 1;
while (left < right) {
if (str1[left] !== str1[right]) {
return false; // Not a palindrome
}
left++;
right--;
}
```
* **`left` and `right`** pointers are initialized to the beginning and end of the normalized string, respectively.
* **`while` loop:** This loop continues as long as the `left` pointer is less than the `right` pointer.
* **Comparison:** Inside the loop, the characters at positions `left` and `right` are compared. If they don't match, the function immediately returns `false` - the string is not a palindrome.
* **Pointer Movement:** If the characters match, the `left` pointer is incremented (moves forward), and the `right` pointer is decremented (moves backward).
**4. Palindrome Confirmation**
```javascript
return true; // It's a palindrome!
```
* If the loop completes without finding any mismatched characters, it means the string reads the same forward and backward. The function returns `true`, indicating it's a palindrome.
**Let me know if you'd like a specific example of how the code works, or if you want it explained in a different way!**
**What is a palindrome?**
A palindrome is a word, phrase, or sequence that reads the same backward as forward. Examples include "racecar", "madam", or "level".
**Explanation of the code:**
**1. Function Declaration**
```javascript
function isPalindrome(str) {
// ...
}
```
* This defines a function called `isPalindrome`, which takes a single input parameter `str` (the string to be checked).
**2. Input Normalization**
```javascript
str1 = str.toLowerCase().replace(/[^a-z0-9]/gi, '');
```
* **`toLowerCase()`:** Converts the input string to lowercase for case-insensitive comparison.
* **`replace(/[^a-z0-9]/gi, '')`:** This regular expression removes all non-alphanumeric characters (letters and numbers) from the string. This ensures we only compare essential characters.
**3. Two-Pointer Comparison**
```javascript
let left = 0;
let right = str1.length - 1;
while (left < right) {
if (str1[left] !== str1[right]) {
return false; // Not a palindrome
}
left++;
right--;
}
```
* **`left` and `right`** pointers are initialized to the beginning and end of the normalized string, respectively.
* **`while` loop:** This loop continues as long as the `left` pointer is less than the `right` pointer.
* **Comparison:** Inside the loop, the characters at positions `left` and `right` are compared. If they don't match, the function immediately returns `false` - the string is not a palindrome.
* **Pointer Movement:** If the characters match, the `left` pointer is incremented (moves forward), and the `right` pointer is decremented (moves backward).
**4. Palindrome Confirmation**
```javascript
return true; // It's a palindrome!
```
* If the loop completes without finding any mismatched characters, it means the string reads the same forward and backward. The function returns `true`, indicating it's a palindrome.
**Let me know if you'd like a specific example of how the code works, or if you want it explained in a different way!**
-----------------------------------//next\\---------------------------------------
//VowelCount*
/*
Implement a function `countVowels` that takes a string as an argument and returns the number of vowels in the string.
Note: Consider both uppercase and lowercase vowels ('a', 'e', 'i', 'o', 'u').
Once you've implemented the logic, test your code by running
*/
function countVowels(str) {
// Your code here
/*
var count = 0;
for (const char of str.toLowerCase()) {
if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
count++;
}
}
return count;
*/
Implement a function `countVowels` that takes a string as an argument and returns the number of vowels in the string.
Note: Consider both uppercase and lowercase vowels ('a', 'e', 'i', 'o', 'u').
Once you've implemented the logic, test your code by running
*/
function countVowels(str) {
// Your code here
/*
var count = 0;
for (const char of str.toLowerCase()) {
if (char === 'a' || char === 'e' || char === 'i' || char === 'o' || char === 'u') {
count++;
}
}
return count;
*/
//'''''''''''''''''''''''''''another solution''''''''''''''''''''''''
/*
const vowels = ['a', 'e', 'i', 'o', 'u'];
// Initialize the count
let count = 0;
// Convert the string to lowercase
// str = str.toLowerCase();
// Iterate over each character in the string
for (let letter of str.toLowerCase()) {
if (vowels.includes(letter)) {
count++;
}
}
// Return the number of vowels
return count;
*/
}
module.exports = countVowels;
// Initialize the count
let count = 0;
// Convert the string to lowercase
// str = str.toLowerCase();
// Iterate over each character in the string
for (let letter of str.toLowerCase()) {
if (vowels.includes(letter)) {
count++;
}
}
// Return the number of vowels
return count;
*/
}
module.exports = countVowels;
---------------------------//Next\\------------------------------------
/*
Write a function that calculates the time (in seconds) it takes for the JS code to calculate sum from 1 to n, given n as the input.
Try running it for
1. Sum from 1-100
2. Sum from 1-100000
3. Sum from 1-1000000000
Hint - use Date class exposed in JS
There is no automated test for this one, this is more for you to understand time goes up as computation goes up
*/
function calculateExecutionTime(n) {
const startTime = new Date().getTime();
const sum = calculateSum(n);
const endTime = new Date().getTime();
const timeElapsed = (endTime - startTime) / 1000;
console.log(`Total sum from 1 to ${n}: ${sum} Time to calculate: ${timeElapsed}`); // Log the sum
Write a function that calculates the time (in seconds) it takes for the JS code to calculate sum from 1 to n, given n as the input.
Try running it for
1. Sum from 1-100
2. Sum from 1-100000
3. Sum from 1-1000000000
Hint - use Date class exposed in JS
There is no automated test for this one, this is more for you to understand time goes up as computation goes up
*/
function calculateExecutionTime(n) {
const startTime = new Date().getTime();
const sum = calculateSum(n);
const endTime = new Date().getTime();
const timeElapsed = (endTime - startTime) / 1000;
console.log(`Total sum from 1 to ${n}: ${sum} Time to calculate: ${timeElapsed}`); // Log the sum
return timeElapsed; // You can still return the time if needed
}
function calculateSum(n) {
return n * (n + 1) / 2;
}
// Test cases
const testValues = [100, 100000, 1000000000];
for (const n of testValues) {
calculateExecutionTime(n);
}
Absolutely! Let's break down the provided JavaScript code step by step.
**Core Functions**
* **`calculateExecutionTime(n)`**
* **Line 1:** `const startTime = new Date().getTime();`
* Stores the current time in milliseconds in the `startTime` variable.
* **Line 2:** `const sum = calculateSum(n);`
* Calls the `calculateSum` function with the input 'n' and stores the returned sum.
* **Line 3:** `const endTime = new Date().getTime();`
* Stores the current time (after calculation) in milliseconds in the `endTime` variable.
* **Line 4:** `const timeElapsed = (endTime - startTime) / 1000; `
* Calculates the difference between `endTime` and `startTime` (in milliseconds), then divides by 1000 to get the time elapsed in seconds.
* **Line 5:** `console.log(`Total sum from 1 to ${n}: ${sum}`);`
* Prints the calculated sum to the console.
* **Line 6:** `console.log(`Time to calculate: ${timeElapsed} seconds`);`
* Prints the time taken for the calculation to the console.
* **`calculateSum(n)`**
* **Line 1:** `return n * (n + 1) / 2;`
* This line implements a mathematical formula to efficiently calculate the sum of numbers from 1 to `n`.
**Test Block**
* **`const testValues = [100, 100000, 1000000000];`**
* Creates an array with test values for the input `n`.
* **`for (const n of testValues) { ... }`**
* This is a `for...of` loop that iterates through each value in the `testValues` array.
* **Line 1:** `calculateExecutionTime(n);`
* Calls the `calculateExecutionTime` function for each value of `n`, measuring and logging the sum and time taken.
**In Summary**
This code snippet elegantly demonstrates how to:
1. Measure the execution time of a code block in JavaScript.
2. Use a clever formula to calculate sums efficiently.
3. Run a small benchmark with different input sizes.
**Let me know if you would like me to clarify any specific part further or have another code snippet you'd like analyzed!**
**Core Functions**
* **`calculateExecutionTime(n)`**
* **Line 1:** `const startTime = new Date().getTime();`
* Stores the current time in milliseconds in the `startTime` variable.
* **Line 2:** `const sum = calculateSum(n);`
* Calls the `calculateSum` function with the input 'n' and stores the returned sum.
* **Line 3:** `const endTime = new Date().getTime();`
* Stores the current time (after calculation) in milliseconds in the `endTime` variable.
* **Line 4:** `const timeElapsed = (endTime - startTime) / 1000; `
* Calculates the difference between `endTime` and `startTime` (in milliseconds), then divides by 1000 to get the time elapsed in seconds.
* **Line 5:** `console.log(`Total sum from 1 to ${n}: ${sum}`);`
* Prints the calculated sum to the console.
* **Line 6:** `console.log(`Time to calculate: ${timeElapsed} seconds`);`
* Prints the time taken for the calculation to the console.
* **`calculateSum(n)`**
* **Line 1:** `return n * (n + 1) / 2;`
* This line implements a mathematical formula to efficiently calculate the sum of numbers from 1 to `n`.
**Test Block**
* **`const testValues = [100, 100000, 1000000000];`**
* Creates an array with test values for the input `n`.
* **`for (const n of testValues) { ... }`**
* This is a `for...of` loop that iterates through each value in the `testValues` array.
* **Line 1:** `calculateExecutionTime(n);`
* Calls the `calculateExecutionTime` function for each value of `n`, measuring and logging the sum and time taken.
**In Summary**
This code snippet elegantly demonstrates how to:
1. Measure the execution time of a code block in JavaScript.
2. Use a clever formula to calculate sums efficiently.
3. Run a small benchmark with different input sizes.
**Let me know if you would like me to clarify any specific part further or have another code snippet you'd like analyzed!**
---------------------------------------------------//Hard Problem\\-----------------------------------------------------
/*
Implement a class `Todo` having below methods
- add(todo): adds todo to list of todos
- remove(indexOfTodo): remove todo from list of todos
- update(index, updatedTodo): update todo at given index
- getAll: returns all todos
- get(indexOfTodo): returns todo at given index
- clear: deletes all todos
Once you've implemented the logic, test your code by running
*/
class Todo {
constructor() {
this.todos = [];
}
// Adds a todo to the list of todos
add(todo) {
this.todos.push(todo);
}
// Removes a todo at the given index
remove(indexOfTodo) {
if (indexOfTodo >= 0 && indexOfTodo < this.todos.length) {
this.todos.splice(indexOfTodo, 1);
}
}
// Updates a todo at the given index
update(index, updatedTodo) {
if (index >= 0 && index < this.todos.length) {
this.todos[index] = updatedTodo;
}
}
// Returns all todos
getAll() {
return this.todos;
}
// Returns the todo at the given index
get(indexOfTodo) {
if (indexOfTodo >= 0 && indexOfTodo < this.todos.length) {
return this.todos[indexOfTodo];
}
return null; // Return null if index is out of bounds
}
// Deletes all todos
clear() {
this.todos = [];
}
}
// Example usage:
// const myTodoList = new Todo();
// myTodoList.add("Buy groceries");
// myTodoList.add("Read a book");
// myTodoList.add("Exercise");
// console.log(myTodoList.getAll()); // ["Buy groceries", "Read a book", "Exercise"]
// myTodoList.update(1, "Finish coding project");
// console.log(myTodoList.get(1)); // "Finish coding project"
// myTodoList.remove(0);
// console.log(myTodoList.getAll()); // ["Finish coding project", "Exercise"]
// myTodoList.clear();
// console.log(myTodoList.getAll()); // []
module.exports = Todo;
Implement a class `Todo` having below methods
- add(todo): adds todo to list of todos
- remove(indexOfTodo): remove todo from list of todos
- update(index, updatedTodo): update todo at given index
- getAll: returns all todos
- get(indexOfTodo): returns todo at given index
- clear: deletes all todos
Once you've implemented the logic, test your code by running
*/
class Todo {
constructor() {
this.todos = [];
}
// Adds a todo to the list of todos
add(todo) {
this.todos.push(todo);
}
// Removes a todo at the given index
remove(indexOfTodo) {
if (indexOfTodo >= 0 && indexOfTodo < this.todos.length) {
this.todos.splice(indexOfTodo, 1);
}
}
// Updates a todo at the given index
update(index, updatedTodo) {
if (index >= 0 && index < this.todos.length) {
this.todos[index] = updatedTodo;
}
}
// Returns all todos
getAll() {
return this.todos;
}
// Returns the todo at the given index
get(indexOfTodo) {
if (indexOfTodo >= 0 && indexOfTodo < this.todos.length) {
return this.todos[indexOfTodo];
}
return null; // Return null if index is out of bounds
}
// Deletes all todos
clear() {
this.todos = [];
}
}
// Example usage:
// const myTodoList = new Todo();
// myTodoList.add("Buy groceries");
// myTodoList.add("Read a book");
// myTodoList.add("Exercise");
// console.log(myTodoList.getAll()); // ["Buy groceries", "Read a book", "Exercise"]
// myTodoList.update(1, "Finish coding project");
// console.log(myTodoList.get(1)); // "Finish coding project"
// myTodoList.remove(0);
// console.log(myTodoList.getAll()); // ["Finish coding project", "Exercise"]
// myTodoList.clear();
// console.log(myTodoList.getAll()); // []
module.exports = Todo;
==============//next\\================
Comments