یک سوال الگوریتمی که توی مصاحبه پرسیدن: (فارسی سازی شده)
صورت مسئله به زبان ساده:
• یه سری کارت داریم که از چپ به راست چیده شدن، مثل:
[-2, 4, -3, 5, -1, 2]
• روی هر کارت یه عدد نوشته شده. میتونه منفی یا مثبت باشه.
• ما از چپ به راست باید کارتها رو انتخاب کنیم.
• با برداشتن هر کارت، عدد اون به “قدرت فعلی” ما اضافه میشه.
• قدرت اولیه ما: 0
• ولی یه قانون مهم داریم:
قدرت ما در هیچ لحظهای نباید صفر یا منفی بشه. اگر بشه، بازی تمومه.
🎯 هدف:
ما باید بیشترین تعداد کارت رو انتخاب کنیم، طوری که قدرتمون همیشه بیشتر از صفر باقی بمونه.
🔍 مثال:
فرض کن کارتها این باشن
کارتها: [3, -2, 4, -5, 2, -1]
قدرت اولیه: 0
قدمبهقدم بریم جلو:
1. کارت 3 → قدرت 0+3 = 3 → خوبه ✅
2. کارت -2 → قدرت 3-2 = 1 → هنوز مثبت ✅
3. کارت 4 → قدرت 1+4 = 5 ✅
4. کارت -5 → قدرت 5-5 = 0 ❌ مجاز نیست → نمیتونیم برداریم
5. کارت 2 → قدرت 5+2 = 7 ✅
6. کارت -1 → قدرت 7-1 = 6 ✅
پس مجموعاً 5 تا کارت برداشتیم و زنده موندیم. 🎉
برای اینکه بتونیم همیشه قدرتمون رو حفظ کنیم، یه روش هوشمند داریم:
1. از چپ به راست حرکت میکنیم.
2. هر کارتی که باعث نشه قدرت صفر یا منفی بشه → برمیداریم.
3. اگه کارت منفی بود، توی یه لیست ذخیره میکنیم.
4. اگه در آینده قراره قدرتمون منفی بشه:
• چک میکنیم بین کارتهای منفی که قبلاً برداشتیم، آیا یکی هست که از کارت فعلی بدتر (منفیتر) باشه؟
• اگه بله → اون کارت بدتر رو حذف میکنیم، کارت فعلی رو میگیریم.
توجه : این روش minHeap واقعی نیست
#interview #algorithm
صورت مسئله به زبان ساده:
• یه سری کارت داریم که از چپ به راست چیده شدن، مثل:
[-2, 4, -3, 5, -1, 2]
• روی هر کارت یه عدد نوشته شده. میتونه منفی یا مثبت باشه.
• ما از چپ به راست باید کارتها رو انتخاب کنیم.
• با برداشتن هر کارت، عدد اون به “قدرت فعلی” ما اضافه میشه.
• قدرت اولیه ما: 0
• ولی یه قانون مهم داریم:
قدرت ما در هیچ لحظهای نباید صفر یا منفی بشه. اگر بشه، بازی تمومه.
🎯 هدف:
ما باید بیشترین تعداد کارت رو انتخاب کنیم، طوری که قدرتمون همیشه بیشتر از صفر باقی بمونه.
🔍 مثال:
فرض کن کارتها این باشن
کارتها: [3, -2, 4, -5, 2, -1]
قدرت اولیه: 0
قدمبهقدم بریم جلو:
1. کارت 3 → قدرت 0+3 = 3 → خوبه ✅
2. کارت -2 → قدرت 3-2 = 1 → هنوز مثبت ✅
3. کارت 4 → قدرت 1+4 = 5 ✅
4. کارت -5 → قدرت 5-5 = 0 ❌ مجاز نیست → نمیتونیم برداریم
5. کارت 2 → قدرت 5+2 = 7 ✅
6. کارت -1 → قدرت 7-1 = 6 ✅
پس مجموعاً 5 تا کارت برداشتیم و زنده موندیم. 🎉
برای اینکه بتونیم همیشه قدرتمون رو حفظ کنیم، یه روش هوشمند داریم:
1. از چپ به راست حرکت میکنیم.
2. هر کارتی که باعث نشه قدرت صفر یا منفی بشه → برمیداریم.
3. اگه کارت منفی بود، توی یه لیست ذخیره میکنیم.
4. اگه در آینده قراره قدرتمون منفی بشه:
• چک میکنیم بین کارتهای منفی که قبلاً برداشتیم، آیا یکی هست که از کارت فعلی بدتر (منفیتر) باشه؟
• اگه بله → اون کارت بدتر رو حذف میکنیم، کارت فعلی رو میگیریم.
توجه : این روش minHeap واقعی نیست
function maxCardCount(cards) {
let power = 0;
let count = 0;
const minHeap = [];
for (let card of cards) {
if (power + card <= 0) {
// Can't pick this card directly — check if we can replace a more negative one
if (card < 0 && minHeap.length > 0 && minHeap[minHeap.length - 1] < card) {
// Replace the most negative card
const removed = minHeap.pop();
power -= removed;
minHeap.push(card);
power += card;
// count stays the same
minHeap.sort((a, b) => a - b); // keep heap sorted
}
continue; // skip if we can’t afford the card
}
// Safe to pick the card
power += card;
count++;
if (card < 0) {
minHeap.push(card);
minHeap.sort((a, b) => a - b);
}
}
return count;
}
#interview #algorithm
اجرا نکرده جواب بدید : خروجی چی میشه؟
#interview #js
async function run() {
console.log('1');
await Promise.resolve();
console.log('2');
}
run();
console.log('3');
#interview #js
اجرا نکرده جواب بدید : خروجی چی میشه؟
#interview #js
let a = { x: 1 };
let b = a;
a.x = 2;
a = { x: 3 };
console.log(b.x);
#interview #js
سوالات مصاحبهای پارت ۱
Q1:
3
3
3
Q2:
0
1
2
Q3:
Hi undefined
Q4:
""
[object Object]
[object Object]
NaN
Q5:
1undefined
Q6:
true
Q7:
false
Q8:
0
2
Q9:
true
false
Q10:
456
Q11:
undefined
Q12:
'51'
4
Q13:
2 1
Q14:
'1,2,34,5,6'
Q15:
ReferenceError: Cannot access 'y' before initialization
Q16:
1
5
3
4
2
Q17:
5
Q18:
A
C
B
Q19:
Ali the code guy
Reza the pilot
Q20:
undefinedthe code guy
Reza the pilot
Q21:
Uncaught ReferenceError: Cannot access 'name' before initialization
Q22:
console.log(a); // ✅ prints: a
console.log(b); // ❌ ReferenceError: b is not defined
console.log(c); // ❌ ReferenceError: c is not defined
console.log(d); // ❌ ReferenceError: d is not defined
console.log(e); // ❌ ReferenceError: e is not defined
console.log(f); // ❌ ReferenceError: f is not defined
Q23:
a
TypeError: b is not a function
Q24:
[5, 5, 5, 5, 5]
Q25:
4
5
6
Q26:
undefined
Q27:
End
Microtask - Promise
Macrotask - Timer
پارت ۲ سوالات:
https://t.iss.one/danceswithcode/4618
@danceswithcode
#interview #js
Q1:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
3
3
3
Q2:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1000);
}
0
1
2
Q3:
const obj = {
name: 'Ali',
sayHi: function () {
setTimeout(function () {
console.log(`Hi ${this.name}`);
}, 1000);
}
};
obj.sayHi();
Hi undefined
Q4:
console.log([] + []);
console.log([] + {});
console.log({} + []);
console.log({} + {});
""
[object Object]
[object Object]
NaN
Q5:
let x = 1;
if (function f() {}) {
x += typeof f;
}
console.log(x);
1undefined
Q6:
console.log([] == ![]);
true
Q7:
console.log([] == []);
false
Q8:
let x = 0;
console.log(x++);
console.log(++x);
0
2
Q9:
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
true
false
Q10:
const a = {};
const b = { key: 'b' };
const c = { key: 'c' };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
456
Q11:
let obj = {
a: 10,
b: () => console.log(this.a)
};
obj.b();
undefined
Q12:
console.log("5" + 1);
console.log("5" - 1);
'51'
4
Q13:
let a = 1;
let b = a++;
console.log(a, b);
2 1
Q14:
console.log([1, 2, 3] + [4, 5, 6]);
'1,2,34,5,6'
Q15:
function test(x = y, y = 2) {
console.log(x, y);
}
test();
ReferenceError: Cannot access 'y' before initialization
Q16:
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3')).then(() => console.log('4'));
console.log('5');
1
5
3
4
2
Q17:
async function test() {
return 5;
}
test().then(console.log);
5
Q18:
Promise.resolve()
.then(() => console.log('A'))
.then(() => console.log('B'));
Promise.resolve().then(() => console.log('C'));
A
C
B
Q19:
var name = "Ali";
(function () {
console.log(name + " the code guy");
name = "Reza";
console.log(name + " the pilot");
})();
Ali the code guy
Reza the pilot
Q20:
var name = "Ali";
(function () {
console.log(name + " the code guy");
var name = "Reza";
console.log(name + " the pilot");
})();
undefinedthe code guy
Reza the pilot
Q21:
var name = "Ali";
(function () {
console.log(name + " the code guy");
let name = "Reza";
console.log(name + " the pilot");
})();
Uncaught ReferenceError: Cannot access 'name' before initialization
Q22:
if (2 == '2') {
var a = 'a';
let b = 'b';
const c = 'c';
}
function func() {
var d = 'd';
let e = 'e';
const f = 'f';
}
func();
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
console.log(f);
console.log(a); // ✅ prints: a
console.log(b); // ❌ ReferenceError: b is not defined
console.log(c); // ❌ ReferenceError: c is not defined
console.log(d); // ❌ ReferenceError: d is not defined
console.log(e); // ❌ ReferenceError: e is not defined
console.log(f); // ❌ ReferenceError: f is not defined
Q23:
a()
b()
c()
function a () {
console.log('a')
}
const b = () => {
console.log('b')
}
var c = function() {
console.log('c')
}
a
TypeError: b is not a function
Q24:
const funcs = [];
for (var i = 0; i < 5; i++) {
funcs.push(() => i);
}
console.log(funcs.map(f => f()));
[5, 5, 5, 5, 5]
Q25:
Promise.resolve().then(() => console.log(1));
queueMicrotask(() => console.log(2));
setTimeout(() => console.log(3), 0);
console.log(4);
new Promise(() => console.log(5));
(async () => console.log(6))();
4
5
6
Q26:
async function foo() {
setTimeout(() => {
return 'done';
}, 1000);
}
foo().then(res => console.log(res));
undefined
Q27:
setTimeout(() => {
console.log('Macrotask - Timer');
}, 0);
Promise.resolve().then(() => {
console.log('Microtask - Promise');
});
console.log('End');
End
Microtask - Promise
Macrotask - Timer
پارت ۲ سوالات:
https://t.iss.one/danceswithcode/4618
@danceswithcode
#interview #js
این یک نکته خاص از ریکت هستش که توی مصاحبهها پرسیده شده ازم:
https://youtube.com/shorts/CAEuTN4qYqI?si=6bo_D8rp8YtYxu_x
#interview
https://youtube.com/shorts/CAEuTN4qYqI?si=6bo_D8rp8YtYxu_x
#interview
۲۰ تا سوال زیر رو سعی کنید بدون هوش مصنوعی و کمک و فقط با فکر کردن ، به روش recursive حل کنید
🟢 Easy
1. Write a recursive function to calculate the sum of numbers from 1 to n.
2. Write a recursive function to compute the factorial of n.
3. Write a recursive function to print each element of an array.
4. Write a recursive function to count down from n to 1.
5. Write a recursive function to reverse a string.
6. Write a recursive function that returns the length of a string (without using .length).
7. Write a recursive function to check if a number is even.
8. Write a recursive function that prints numbers from 1 up to n.
9. Write a recursive function to count the number of vowels in a string.
10 .Write a recursive function to calculate the power base^exponent.
🟡 Medium
11. Write a recursive function to compute the nth Fibonacci number.
12. Write a recursive function to check if a string is a palindrome.
13. Write a recursive function to sum all elements in a nested array (deep sum).
14. Write a recursive function to flatten a nested array into a single array.
15. Write a recursive function to find the maximum number in an array.
16. Write a recursive function that capitalizes the first letter of each word in an array of strings.
17. Write a recursive function to multiply all numbers in an array.
18. Write a recursive function that removes all occurrences of a given character from a string.
19. Write a recursive function to find the GCD (greatest common divisor) of two numbers.
20. Write a recursive function to merge two sorted arrays into one sorted array (without using loops).
@alithecodeguy #recursive #interview
🟢 Easy
1. Write a recursive function to calculate the sum of numbers from 1 to n.
2. Write a recursive function to compute the factorial of n.
3. Write a recursive function to print each element of an array.
4. Write a recursive function to count down from n to 1.
5. Write a recursive function to reverse a string.
6. Write a recursive function that returns the length of a string (without using .length).
7. Write a recursive function to check if a number is even.
8. Write a recursive function that prints numbers from 1 up to n.
9. Write a recursive function to count the number of vowels in a string.
10 .Write a recursive function to calculate the power base^exponent.
🟡 Medium
11. Write a recursive function to compute the nth Fibonacci number.
12. Write a recursive function to check if a string is a palindrome.
13. Write a recursive function to sum all elements in a nested array (deep sum).
14. Write a recursive function to flatten a nested array into a single array.
15. Write a recursive function to find the maximum number in an array.
16. Write a recursive function that capitalizes the first letter of each word in an array of strings.
17. Write a recursive function to multiply all numbers in an array.
18. Write a recursive function that removes all occurrences of a given character from a string.
19. Write a recursive function to find the GCD (greatest common divisor) of two numbers.
20. Write a recursive function to merge two sorted arrays into one sorted array (without using loops).
@alithecodeguy #recursive #interview
رقصنده با کد
سوالات مصاحبهای پارت ۱ Q1: for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 3 3 3 Q2: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 0 1 2 Q3: const obj = { name: 'Ali', sayHi: function () {…
پارت ۲ سوالات مصاحبهای
پارت ۱:
https://t.iss.one/danceswithcode/4445
این پست به مرور زمان تکمیل میشه
Q28:
*One*
*Two*
*Four*
*Three*
Q29:
*One*
*Two*
*Four*
Q30:
پیاده سازی Promise.all
Q31:
Debounce in JavaScript
Q32:
Throttling in JavaScript
Q33:
DeepClone using recursion
Q34:
Check if a string is a palindrome (ignoring cases and spaces).
function isPalindrome(str){
.....
}
use two-pointer to solve it
@danceswithcode
#interview #js
پارت ۱:
https://t.iss.one/danceswithcode/4445
این پست به مرور زمان تکمیل میشه
Q28:
const myPromise = new Promise((resolveOuter) => {
console.log("*One*");
resolveOuter(
new Promise((resolveInner) => {
console.log("*Two*");
setTimeout(() => resolveInner("*Three*"), 0);
})
);
});
const func1 = () => {
myPromise.then((res) => res).then((res2) => console.log(res2));
};
console.log("*Four*");
func1();
*One*
*Two*
*Four*
*Three*
Q29:
const myPromise = new Promise((resolveOuter) => {
console.log("*One*");
resolveOuter(
new Promise((resolveInner) => {
console.log("*Two*");
setTimeout(() => resolveInner("*Three*"), 0);
})
);
});
const func1 = () => {
myPromise.then((res) => res).then((res2) => console.log(res2));
};
console.log("*Four*");
*One*
*Two*
*Four*
Q30:
پیاده سازی Promise.all
function promiseAll(promises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(promises)) {
return reject(new TypeError('Input must be an array'));
}
const results = [];
let completed = 0;
if (promises.length === 0) {
return resolve([]);
}
promises.forEach((p, index) => {
Promise.resolve(p)
.then((value) => {
results[index] = value;
completed++;
if (completed === promises.length) {
resolve(results);
}
})
.catch((err) => reject(err));
});
});
}
Q31:
Debounce in JavaScript
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
Q32:
Throttling in JavaScript
function throttle(func, delay) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
func.apply(this, args);
}
};
}
Q33:
DeepClone using recursion
function deepClone(obj, hash = new WeakMap()) {
if (Object(obj) !== obj) return obj; // primitives
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
if (hash.has(obj)) return hash.get(obj); // circular
const result = Array.isArray(obj) ? [] : {};
hash.set(obj, result);
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key], hash);
}
}
return result;
}
Q34:
Check if a string is a palindrome (ignoring cases and spaces).
function isPalindrome(str){
.....
}
use two-pointer to solve it
function isPalindrome(str) {
// Normalize the string: remove non-alphanumerics and make lowercase
const cleanStr = str.replace(/[^a-z0-9]/gi, '').toLowerCase();
let left = 0;
let right = cleanStr.length - 1;
while (left < right) {
if (cleanStr[left] !== cleanStr[right]) {
return false; // mismatch found
}
left++;
right--;
}
return true;
}
@danceswithcode
#interview #js
💡 اصول SOLID چیست؟ (به زبان ساده و با مثالهای جاوااسکریپتی)
اصول SOLID پنج اصل کلیدی در طراحی شیءگرا (Object-Oriented Design) هست که کمک میکنه کدت:
• قابل توسعه باشه (افزودن ویژگی جدید راحت باشه)
• قابل نگهداری باشه (تغییرات خراب نکنه)
• قابل تست باشه (نوشتن تست سادهتر بشه)
• و خواناتر و منظمتر باشه
این اصول توسط Robert C. Martin (Uncle Bob) معرفی شدند، و پایهای برای نوشتن کد تمیز (Clean Code) هستند.
کلمه SOLID مخفف ۵ اصل زیره:
------------------------
🔹 1 — Single Responsibility Principle (SRP)
اصل مسئولیت یکتا
A class should have one, and only one, reason to change.
🔸 یعنی هر کلاس یا ماژول فقط یک وظیفهی مشخص باید داشته باشه. اگر چند کار مختلف انجام بده، تغییر در یکی ممکنه کل کلاس رو خراب کنه.
✅ مثال صحیح :
------------------------
🔹 2 — Open/Closed Principle (OCP)
اصل باز برای توسعه، بسته برای تغییر
Software entities should be open for extension, but closed for modification.
🔸 یعنی باید بتونی بدون تغییر دادن کد قبلی، رفتار جدیدی بهش اضافه کنی (مثلاً با ارثبری یا ترکیب کلاسها).
✅ مثال صحیح :
------------------------
🔹 3 — Liskov Substitution Principle (LSP)
اصل جایگزینی لیسکوف
Subtypes must be substitutable for their base types without breaking the program.
🔸 یعنی کلاس فرزند باید بتونه بدون خراب کردن منطق برنامه، جای کلاس والد استفاده بشه.
✅ مثال صحیح :
❌ مثال نادرست:
------------------------
🔹 4 — Interface Segregation Principle (ISP)
اصل تفکیک واسطها
Clients should not be forced to depend on interfaces they do not use.
🔸 یعنی به جای ساختن یک کلاس یا اینترفیس بزرگ، چند تای کوچکتر بساز که فقط نیازهای خاص رو پوشش بده.
✅ مثال صحیح :
------------------------
🔹 5 — Dependency Inversion Principle (DIP)
اصل وارونگی وابستگی
High-level modules should not depend on low-level modules. Both should depend on abstractions.
🔸 یعنی کدهای سطح بالا نباید مستقیماً به جزئیات پیادهسازی وابسته باشن؛ باید به abstraction (مثل interface) وابسته باشن.
✅ مثال صحیح :
مطالب بیشتر در کانال رقصنده با کد:
https://t.iss.one/danceswithcode
#interview #solid @alithecodeguy
اصول SOLID پنج اصل کلیدی در طراحی شیءگرا (Object-Oriented Design) هست که کمک میکنه کدت:
• قابل توسعه باشه (افزودن ویژگی جدید راحت باشه)
• قابل نگهداری باشه (تغییرات خراب نکنه)
• قابل تست باشه (نوشتن تست سادهتر بشه)
• و خواناتر و منظمتر باشه
این اصول توسط Robert C. Martin (Uncle Bob) معرفی شدند، و پایهای برای نوشتن کد تمیز (Clean Code) هستند.
کلمه SOLID مخفف ۵ اصل زیره:
------------------------
🔹 1 — Single Responsibility Principle (SRP)
اصل مسئولیت یکتا
A class should have one, and only one, reason to change.
🔸 یعنی هر کلاس یا ماژول فقط یک وظیفهی مشخص باید داشته باشه. اگر چند کار مختلف انجام بده، تغییر در یکی ممکنه کل کلاس رو خراب کنه.
✅ مثال صحیح :
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
class UserRepository {
save(user) {
// save to database
}
}
------------------------
🔹 2 — Open/Closed Principle (OCP)
اصل باز برای توسعه، بسته برای تغییر
Software entities should be open for extension, but closed for modification.
🔸 یعنی باید بتونی بدون تغییر دادن کد قبلی، رفتار جدیدی بهش اضافه کنی (مثلاً با ارثبری یا ترکیب کلاسها).
✅ مثال صحیح :
class Discount {
calculate(price) {
return price;
}
}
class GoldDiscount extends Discount {
calculate(price) {
return price * 0.8;
}
}
------------------------
🔹 3 — Liskov Substitution Principle (LSP)
اصل جایگزینی لیسکوف
Subtypes must be substitutable for their base types without breaking the program.
🔸 یعنی کلاس فرزند باید بتونه بدون خراب کردن منطق برنامه، جای کلاس والد استفاده بشه.
✅ مثال صحیح :
class Bird {
makeSound() {
console.log("chirp");
}
}
class Parrot extends Bird {}
function playSound(bird) {
bird.makeSound();
}
playSound(new Parrot()); // درست کار میکنه
❌ مثال نادرست:
class Ostrich extends Bird {
fly() {
throw new Error("Can't fly");
}
}
------------------------
🔹 4 — Interface Segregation Principle (ISP)
اصل تفکیک واسطها
Clients should not be forced to depend on interfaces they do not use.
🔸 یعنی به جای ساختن یک کلاس یا اینترفیس بزرگ، چند تای کوچکتر بساز که فقط نیازهای خاص رو پوشش بده.
✅ مثال صحیح :
class Printer {
print() {}
}
class Scanner {
scan() {}
}
class AllInOneMachine {
constructor(printer, scanner) {
this.printer = printer;
this.scanner = scanner;
}
}
------------------------
🔹 5 — Dependency Inversion Principle (DIP)
اصل وارونگی وابستگی
High-level modules should not depend on low-level modules. Both should depend on abstractions.
🔸 یعنی کدهای سطح بالا نباید مستقیماً به جزئیات پیادهسازی وابسته باشن؛ باید به abstraction (مثل interface) وابسته باشن.
✅ مثال صحیح :
class EmailService {
send(msg) {
console.log("Sending email:", msg);
}
}
class Notifier {
constructor(service) {
this.service = service;
}
notify(message) {
this.service.send(message);
}
}
const email = new EmailService();
const notifier = new Notifier(email);
notifier.notify("Hello!");
مطالب بیشتر در کانال رقصنده با کد:
https://t.iss.one/danceswithcode
#interview #solid @alithecodeguy