Skip to content

Commit ab921e8

Browse files
committed
JS interview coding question
0 parents  commit ab921e8

File tree

162 files changed

+4855
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

162 files changed

+4855
-0
lines changed

AddDigits.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const AddDigits = (num) =>{
2+
while (num >= 10) {
3+
let sum = 0;
4+
while (num > 0) {
5+
sum += num % 10;
6+
num = Math.floor(num / 10);
7+
}
8+
num = sum;
9+
}
10+
return num;
11+
}
12+
console.log(AddDigits(38))

AddToArray.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
let array1 = [1,2,3,4,5,6,7,8]
2+
let array2 = [2,3,4,5,6,7,8,9]
3+
let result = []
4+
for(let i=0; i<array1.length; i++){
5+
for(let j=0; j<array2.length; j++){
6+
let add = array1[i] + array2[2];
7+
result.push(add)
8+
}
9+
}
10+
11+
console.log(result)

Array/arrayreplace.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function solution(inputArray, elemToReplace, substitutionElem) {
2+
if(inputArray.length < 0) return inputArray
3+
let arr = []
4+
for(let i=0; i<inputArray.length; i++){
5+
if(inputArray && inputArray[i] === elemToReplace){
6+
arr.splice(i,0,substitutionElem)
7+
}else{
8+
arr.push(inputArray[i])
9+
}
10+
}
11+
return arr
12+
}
13+
14+
let inputArray = [1, 2, 1], elemToReplace = 1, substitutionElem = 3
15+
console.log(solution(inputArray,elemToReplace,substitutionElem))

Array/checkEvenOrOdd.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
function solution(n) {
2+
if(n <= 1) return false;
3+
4+
if(n % 2 === 0){
5+
return true;
6+
}
7+
return false
8+
}
9+
let n = 2;
10+
console.log(solution(n))

Array/checkVariable.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
function solution(name) {
2+
// Check if the name starts with a digit
3+
if (/^\d/.test(name)) {
4+
return false;
5+
}
6+
7+
// Check if the name contains only valid characters
8+
if (/^[a-zA-Z0-9_]+$/.test(name)) {
9+
return true;
10+
} else {
11+
return false;
12+
}
13+
}
14+
15+
let name = "var_1__Int";
16+
// let name = "qq-q"
17+
console.log(solution(name))

Array/chessMaster.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
function solution(cell1, cell2) {
2+
// Extract the row and column numbers for each cell
3+
const [row1, col1] = [parseInt(cell1[1]), cell1.charCodeAt(0) - 64];
4+
const [row2, col2] = [parseInt(cell2[1]), cell2.charCodeAt(0) - 64];
5+
6+
// Check if the sum of the row and column numbers is even for both cells
7+
return (row1 + col1) % 2 === (row2 + col2) % 2;
8+
}

Array/circleOfNum.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
function circleOfNumbers(n, firstNumber) {
2+
// Calculate the number opposite to firstNumber using modulo arithmetic
3+
const oppositeNumber = (firstNumber + n/2) % n;
4+
5+
return oppositeNumber;
6+
}
7+

Array/evenNumbers.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const evenNumbers = (arr) =>{
2+
let result = [];
3+
for(let i=0; i< arr.length; i++){
4+
if(arr[i] % 2 === 0){
5+
result.push(arr[i])
6+
}
7+
}
8+
return result
9+
}
10+
11+
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
12+
const evens = evenNumbers(arr);
13+
console.log(evens); // output: [2, 4, 6, 8, 10]
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const findDuplicateSortIncreasingOrder = (arr)=>{
2+
let unique = []
3+
let duplicate = []
4+
for(let i=0; i<arr.length; i++){
5+
if(!unique.includes(arr[i])){
6+
unique.push(arr[i])
7+
}else{
8+
duplicate.push(arr[i])
9+
}
10+
}
11+
let res = duplicate.sort((a,b)=>a-b)
12+
return res
13+
}
14+
let arr = [2,3,4,5,5,6,7,2,21,1,1,7,8,9,10]
15+
console.log(findDuplicateSortIncreasingOrder(arr))

Array/findNumbersInArray.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const findNumbersInArray = (arr, find)=>{
2+
let count = 0;
3+
for(let i=0; i<arr.length; i++){
4+
if(arr[i] === find){
5+
count ++;
6+
}
7+
}
8+
return count
9+
}
10+
11+
const arr = [1, 5, 2, 5, 3, 5, 4];
12+
const find = 5;
13+
const count = findNumbersInArray(arr, find);
14+
console.log(count); // output: 3

Array/getMedianArray.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const getMedian = (arr)=>{
2+
let sortedArray = arr.sort((a,b)=>{ return a-b })
3+
let minIndex = Math.floor(sortedArray.length/2);
4+
if(sortedArray.length % 2 === 0){
5+
return (sortedArray[minIndex -1] + sortedArray[minIndex]) / 2
6+
}
7+
else{
8+
return sortedArray[minIndex]
9+
}
10+
}
11+
12+
13+
const arr = [1, 2, 3, 4, 5];
14+
const median = getMedian(arr);
15+
console.log(median); // output: 3
16+
17+
const arr2 = [1, 2, 3, 4, 5, 6];
18+
const median2 = getMedian(arr2);
19+
console.log(median2); // output: 3.5

Array/getUnique.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const getUniqueElements = (arr) =>{
2+
let result = [];
3+
for(let i=0; i<arr.length; i++){
4+
if(arr.indexOf(arr[i]) === arr.lastIndexOf(arr[i])){
5+
result.push(arr[i])
6+
}
7+
}
8+
return result
9+
}
10+
const arr = [1, 2, 3, 2, 4, 5, 1, 6, 7, 5];
11+
const uniqueArr = getUniqueElements(arr);
12+
console.log(uniqueArr); // output: [3, 4, 6, 7]

Array/intersection.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const intersection = (arr1,arr2) =>{
2+
let result = []
3+
for(let i=0; i<arr1.length; i++){
4+
for(let j=0; j<arr2.length; j++){
5+
if(arr1[i] === arr2[j]){
6+
result.push(arr1[i])
7+
}
8+
}
9+
}
10+
return result;
11+
}
12+
13+
14+
const arr1 = [1, 2, 3, 4, 5];
15+
const arr2 = [3, 4, 5, 6, 7];
16+
const common = intersection(arr1, arr2);
17+
console.log(common); // output: [3, 4, 5]

Array/largestNumber.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
const largestNumber = (arr)=>{
2+
let largest = [0]
3+
for(let i=0; i<arr.length; i++){
4+
if(arr[i] > largest){
5+
largest = arr[i]
6+
}
7+
}
8+
return largest
9+
}
10+
11+
12+
const arr = [10, 5, 2, 20, 8];
13+
const largest = largestNumber(arr);
14+
console.log(largest); // output: 20

Array/mergeSorted.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
2+
// Output: [1,2,2,3,5,6]
3+
4+
const mergeSortedArray = (arr1,arr2)=>{
5+
let result = []
6+
let mergeArray = [...arr1,...arr2]
7+
for(let i=0; i<mergeArray.length; i++){
8+
if(mergeArray[i] !== 0){
9+
result.push(mergeArray[i])
10+
}
11+
}
12+
13+
return result.sort((a,b)=> { return a - b})
14+
}
15+
16+
console.log(mergeSortedArray([1,2,3,0,0,0],[2,5,6]))

Array/mongoDB/chapter.md

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
## What is sharding in MongoDB?
2+
3+
Sharding is a method for distributing data across multiple machines. MongoDB uses sharding to support deployments with very large data sets and high throughput operations. Database systems with large data sets or high throughput applications can challenge the capacity of a single server.
4+
5+
sharding is a technique used in MongoDB to horizontally partition data across multiple servers or "shards". This is done to scale MongoDB horizontally, by distributing the data across multiple machines
6+
7+
8+
# Key Features of MongoDB
9+
Some of the key features of MongoDB are as follows:
10+
11+
Schema-less database
12+
Document Oriented
13+
Indexing
14+
Sharding
15+
16+
17+
## How does MongoDB ensure high availability and data durability?
18+
---
19+
20+
21+
# Indexing
22+
Indexing helps in improving the performance of search queries. When you continuously perform searches in MongoDB documents, you can index those files which match your search criteria. Therefore, in MongoDB documents, users can index any field with primary or secondary indices, making the query search faster.
23+
24+
# Sharding
25+
Sharding in MongoDB is performed when you want to work with larger datasets. With sharding, you can distribute such large data to multiple MongoDB instances. The collections in MongoDB having larger sizes are distributed in multiple collections, called ‘shards.’ Shards are implemented through clusters.
26+
27+
# What is the role of indexes in MongoDB?
28+
29+
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement.
30+
31+
32+
# Stages of MongoDB Aggregation Pipeline
33+
$project.
34+
$match.
35+
$group.
36+
$sort.
37+
$skip & $limit.
38+
$first & $last.
39+
$unwind.
40+
41+
# What is aggregation in MongoDB?
42+
What is Aggregation in MongoDB? Aggregation is a way of processing a large number of documents in a collection by means of passing them through different stages. The stages make up what is known as a pipeline. The stages in a pipeline can filter, sort, group, reshape and modify documents that pass through the pipeline.
43+
44+
45+
# How does MongoDB handle transactions?
46+
47+
MongoDB supports multi-document transactions for replica sets and sharded clusters in version 4.0 and later. Transactions allow for atomic, consistent, isolated, and durable (ACID) operations on multiple documents within a single transaction.
48+
49+
To use transactions in MongoDB, you need to follow these steps:
50+
51+
Start a transaction: You can start a transaction by calling the startSession() method to create a session, and then calling the startTransaction() method on the session object.
52+
53+
Perform transactional operations: Within a transaction, you can perform read and write operations on multiple documents and collections as if they were a single operation.
54+
55+
Commit or abort the transaction: If all operations in the transaction succeed, you can call the commitTransaction() method to commit the transaction. If any operation fails, you can call the abortTransaction() method to roll back the entire transaction.
56+
57+
MongoDB uses a two-phase commit protocol to ensure that transactions are atomic and durable. In the first phase, the transaction coordinator (which could be a mongos instance or a replica set primary) asks each shard to prepare for the commit by validating the transaction and making sure that all the necessary changes can be made. In the second phase, the coordinator instructs each shard to commit the transaction and persist the changes to disk.
58+
59+
It's important to note that transactions in MongoDB have some limitations and requirements. For example, all documents that are part of a transaction must belong to the same replica set or sharded cluster, and you cannot perform certain operations within a transaction, such as creating or dropping a collection or index.
60+
61+
Overall, MongoDB's support for transactions provides a powerful tool for ensuring data integrity and consistency in complex operations that span multiple documents and collections.
62+
63+
64+
# Here are some best practices for MongoDB performance optimization:
65+
66+
Indexing: Create indexes on fields that are frequently queried and ensure that your queries are using the correct indexes. Use the explain() method to analyze the performance of your queries and identify slow queries that need optimization.
67+
68+
Schema design: Design your data schema to match the query patterns of your application. Denormalize data if necessary to reduce the number of joins required for your queries. Avoid using overly complex data structures, such as arrays with large numbers of elements.
69+
70+
Sharding: Use sharding to distribute your data across multiple nodes to achieve better scalability and performance. Choose an appropriate shard key that evenly distributes your data across the cluster and avoids hotspots.
71+
72+
Server configuration: Configure your MongoDB servers to use the appropriate hardware and operating system settings. Use SSDs for storage to improve read and write performance. Use the WiredTiger storage engine for improved performance and compression.
73+
74+
Monitoring: Monitor your MongoDB deployment to identify performance issues and potential bottlenecks. Use tools like MongoDB Compass, the mongostat and mongotop command-line utilities, and third-party monitoring tools to track performance metrics like CPU usage, memory usage, and disk I/O.
75+
76+
Compression: Use compression to reduce the size of your data and improve read and write performance. MongoDB supports both document-level compression and storage engine-level compression.
77+
78+
Query optimization: Optimize your queries by reducing the amount of data returned, using projection to select only the fields you need, and limiting the number of results returned with pagination or aggregation.
79+
80+
Caching: Use caching to reduce the number of queries to the database. Use caching solutions like Redis or Memcached to store frequently accessed data in memory.
81+
82+
By following these best practices, you can optimize the performance of your MongoDB deployment and achieve better scalability, faster query performance, and improved data management.
83+
84+
# MongoDB supports several data models, including:
85+
86+
Document model
87+
Key-value model
88+
Graph model
89+
Tabular model: MongoDB supports a tabular data model through the use of the MongoDB Connector for BI
90+
91+
92+
# What is the role of a replica set in MongoDB?
93+
94+
A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets provide redundancy and high availability, and are the basis for all production deployments
95+

Array/nonDecreasingOrder.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// takes an array of integers and returns true if the array is sorted in non-decreasing order, false otherwise:
2+
const isNonDecreasing = (arr)=>{
3+
for(let i=0; i<arr.length; i++){
4+
if(arr[i] > arr[i+1]){
5+
return false;
6+
}
7+
}
8+
return true;
9+
}
10+
11+
12+
13+
const arr1 = [1, 2, 3, 4, 5];
14+
const arr2 = [1, 2, 5, 3, 4];
15+
const isNonDecreasing1 = isNonDecreasing(arr1);
16+
const isNonDecreasing2 = isNonDecreasing(arr2);
17+
console.log(isNonDecreasing1); // output: true
18+
console.log(isNonDecreasing2); // output: false

Array/removeDuplicates.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// const removeDuplicates = (arr) =>{
2+
// return [...new Set(arr)]
3+
// }
4+
5+
// console.log(removeDuplicates([1,1,2]))
6+
7+
const removeDuplicates1 = (arr) =>{
8+
let result = []
9+
arr.sort((a,b)=>{ return a-b})
10+
for(let i=0; i<arr.length; i++){
11+
if(!result.includes(arr[i])){
12+
result.push(arr[i])
13+
}
14+
}
15+
return result
16+
}
17+
18+
console.log(removeDuplicates1([1,1,2,9,9]))

Array/removeElement.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// nums = [3,2,2,3], val = 3
2+
3+
const removeElement = (arr, val)=>{
4+
let count = 0;
5+
for(let i=0; i<arr.length; i++){
6+
if(arr[i] !== val){
7+
count ++;
8+
arr[count] = arr[i]
9+
}
10+
}
11+
return count;
12+
}
13+
14+
console.log(removeElement([3,2,2,3],3))

Array/replaceStrinfs.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// For inputString = "crazy", the output should be solution(inputString) = "dsbaz"
2+
function solution(inputString) {
3+
let str = ""
4+
for(let i=0; i < inputString.length; i++){
5+
let char = inputString[i]
6+
if(char !== "z"){
7+
let inc = char.charCodeAt(0) + 1;
8+
let nextChar = String.fromCharCode(inc).toLowerCase();
9+
str+=nextChar;
10+
}else{
11+
let inc = 97;
12+
let nextChar = String.fromCharCode(inc).toLowerCase();
13+
str+=nextChar;
14+
}
15+
}
16+
return str
17+
}
18+
19+
console.log(solution("crazy"))

0 commit comments

Comments
 (0)