Сайт: https://easyoffer.ru/
Все каналы: t.me/+xGeAw6ckJ4liYzQy
Контакт для рекламы: @sendme_ads
Post #2571
55
This post (sticker, poll or similar) has no web preview. Open in Telegram
JA @easy_frontend_task
This post (sticker, poll or similar) has no web preview. Open in Telegram
Input: barcodes = [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
function rearrangeBarcodes(barcodes) {
const count = new Map();
for (const barcode of barcodes) {
count.set(barcode, (count.get(barcode) || 0) + 1);
}
const maxHeap = [];
for (const [barcode, freq] of count) {
maxHeap.push([-freq, barcode]);
}
maxHeap.sort((a, b) => a[0] - b[0]);
const result = [];
let prevFreq = 0;
let prevBarcode = null;
while (maxHeap.length) {
const [freq, barcode] = maxHeap.pop();
result.push(barcode);
if (prevFreq < 0) {
maxHeap.push([prevFreq, prevBarcode]);
maxHeap.sort((a, b) => a[0] - b[0]);
}
prevFreq = freq + 1;
prevBarcode = barcode;
}
return result;
}Input: function_id = 1, z = 5
Output: [[1,4],[2,3],[3,2],[4,1]]
class CustomFunction {
f(x, y) {}
}
var findSolution = function(customfunction, z) {
let result = [];
let x = 1;
let y = 1000;
while (x <= 1000 && y >= 1) {
let value = customfunction.f(x, y);
if (value === z) {
result.push([x, y]);
x++;
} else if (value < z) {
x++;
} else {
y--;
}
}
return result;
};
n. Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
dummy, указывающий на head. Инициализируем два указателя — fast и slow на dummy. fast на n шагов вперёд. fast и slow одновременно, пока fast не дойдёт до конца списка. slow.next указывает на узел, который нужно удалить. slow.next, чтобы пропустить этот узел. Возвращаем dummy.next как новую голову.var removeNthFromEnd = function (head, n) {
const dummy = new ListNode(0, head);
let fast = dummy, slow = dummy;
while (n--) {
fast = fast.next;
}
while (fast.next) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
};Input: workers = [[0,0],[2,1]], bikes = [[1,2],[3,3]]
Output: [1,0]
function assignBikes(workers, bikes) {
const pairs = [];
for (let i = 0; i < workers.length; i++) {
for (let j = 0; j < bikes.length; j++) {
const distance = Math.abs(workers[i][0] - bikes[j][0]) + Math.abs(workers[i][1] - bikes[j][1]);
pairs.push([distance, i, j]);
}
}
pairs.sort((a, b) => {
if (a[0] !== b[0]) return a[0] - b[0];
if (a[1] !== b[1]) return a[1] - b[1];
return a[2] - b[2];
});
const result = Array(workers.length).fill(-1);
const bikeTaken = Array(bikes.length).fill(false);
const workerAssigned = Array(workers.length).fill(false);
for (const [distance, workerIdx, bikeIdx] of pairs) {
if (!workerAssigned[workerIdx] && !bikeTaken[bikeIdx]) {
result[workerIdx
Input: arr = ["un","iq","ue"]
Output: 4
var maxLength = function(arr) {
const isUnique = s => new Set(s).size === s.length;
const backtrack = (index, current) => {
if (!isUnique(current)) return 0;
let maxLength = current.length;
for (let i = index; i < arr.length; i++) {
maxLength = Math.max(maxLength, backtrack(i + 1, current + arr[i]));
}
return maxLength;
};
return backtrack(0, "");
};Input: n = 1
Output: true
Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
var winnerSquareGame = function(n) {
const cache = new Map();
cache.set(0, false);
const dfs = (remain) => {
if (cache.has(remain)) {
return cache.get(remain);
}
const sqrtRoot = Math.floor(Math.sqrt(remain));
for (let i = 1; i <= sqrtRoot; i++) {
if (!dfs(remain - i * i)) {
cache.set(remain, true);
return true;
}
}
cache.set(remain, false);
return false;
};
return dfs(n);
};Input: items = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]]
Output: [[1,100],[7,100]]
var highFive = function(items) {
const K = 5;
items.sort((a, b) => {
if (a[0] !== b[0]) return a[0] - b[0];
return b[1] - a[1];
});
const solution = [];
let i = 0;
while (i < items.length) {
const id = items[i][0];
let sum = 0;
for (let k = i; k < i + K; k++) {
sum += items[k][1];
}
while (i < items.length && items[i][0] === id) {
i++;
}
solution.push([id, Math.floor(sum / K)]);
}
return solution;
};Input: prices = ["0.700","2.800","4.900"], target = 8
Output: "1.000"
function minimizeRoundingError(prices, target) {
let floors = prices.map(p => Math.floor(parseFloat(p)));
let totalFloor = floors.reduce((a, b) => a + b, 0);
let difference = target - totalFloor;
if (difference < 0 || difference > prices.length) {
return "-1";
}
let roundingErrors = prices.map((p, i) => [Math.ceil(parseFloat(p)) - floors[i], parseFloat(p) - floors[i]]);
roundingErrors.sort((a, b) => a[1] - b[1]);
let roundingErrorSum = floors.reduce((sum, floor, i) => sum + (floor - parseFloat(prices[i])), 0);
for (let i = 0; i < difference; i++) {
roundingErrorSum += roundingErrors[i][1];
}
return roundingErrorSum.toFixed(3);
}Input: n = 1, k = 2
Output: "10"
var crackSafe = function(n, k) {
const seen = new Set();
const result = [];
const dfs = (node) => {
for (let x = 0; x < k; x++) {
const neighbor = node + x;
if (!seen.has(neighbor)) {
seen.add(neighbor);
dfs(neighbor.slice(1));
result.push(x);
}
}
};
const startNode = '0'.repeat(n - 1);
dfs(startNode);
return startNode + result.join('');
};Input: nums = [5,3,2,4]
Output: 0
Explanation: We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes [5,3,3,4].
In the second move, change 4 to 3. nums becomes [5,3,3,3].
In the third move, change 5 to 3. nums becomes [3,3,3,3].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
var minDifference = function(nums) {
const numsSize = nums.length
if (numsSize <= 4) return 0
nums.sort((a, b) => a - b)
let minDiff = Infinity
for (let left = 0; left < 4; left++) {
const right = numsSize - 4 + left
minDiff = Math.min(minDiff, nums[right] - nums[left])
}
return minDiff
}Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation:
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"
class Solution {
removeDuplicates(s, k) {
let counts = [];
let sa = s.split('');
let j = 0;
for (let i = 0; i < sa.length; ++i, ++j) {
sa[j] = sa[i];
if (j === 0 || sa[j] !== sa[j - 1]) {
counts.push(1);
} else {
let incremented = counts.pop() + 1;
if (incremented === k) {
j -= k;
} else {
counts.push(incremented);
}
}
}
return sa.slice(0, j).join('');
}
}Input: nums = [10,2]
Output: "210"
class Solution {
largestNumber(nums) {
const strNums = nums.map(String);
strNums.sort((a, b) => (b + a).localeCompare(a + b));
if (strNums[0] === "0") {
return "0";
}
return strNums.join('');
}
}Input: nums = [3,5,2,6], k = 2
Output: [2,6]
Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.
var mostCompetitive = function(nums, k) {
let queue = [];
let additionalCount = nums.length - k;
for (let num of nums) {
while (queue.length > 0 && queue[queue.length - 1] > num && additionalCount > 0) {
queue.pop();
additionalCount--;
}
queue.push(num);
}
return queue.slice(0, k);
};Input:
RequestAccepted table:
+--------------+-------------+-------------+
| requester_id | accepter_id | accept_date |
+--------------+-------------+-------------+
| 1 | 2 | 2016/06/03 |
| 1 | 3 | 2016/06/08 |
| 2 | 3 | 2016/06/08 |
| 3 | 4 | 2016/06/09 |
+--------------+-------------+-------------+
Output:
+----+-----+
| id | num |
+----+-----+
| 3 | 3 |
+----+-----+
Explanation:
The person with id 3 is a friend of people 1, 2, and 4, so he has three friends in total, which is the most number than any others.
WITH Combined AS (
SELECT requester_id AS id
FROM friendships
UNION ALL
SELECT accepter_id AS id
FROM friendships
),
FriendCounts AS (
SELECT id, COUNT(*) AS friend_count
FROM Combined
GROUP BY id
ORDER BY friend_count DESC
)
SELECT id, friend_count
FROM FriendCounts
LIMIT 1;
words, верните максимальное значение произведения длины word[i] на длину word[j], где два слова не имеют общих букв. Если таких двух слов не существует, верните 0.Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".
var maxProduct = function(words) {
const n = words.length;
const masks = new Array(n).fill(0);
const lens = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
let bitmask = 0;
for (const ch of words[i]) {
bitmask |= 1 << (ch.charCodeAt(0) - 'a'.charCodeAt(0));
}
masks[i] = bitmask;
lens[i] = words[i].length;
}
let maxVal = 0;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if ((masks[i] & masks[j]) === 0) {
maxVal = Math.max(maxVal, lens[i] * lens[j]);
}
}
}
return maxVal;
};Input
["CombinationIterator", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[["abc", 2], [], [], [], [], [], []]
Output
[null, "ab", true, "ac", true, "bc", false]
Explanation
CombinationIterator itr = new CombinationIterator("abc", 2);
itr.next(); // return "ab"
itr.hasNext(); // return True
itr.next(); // return "ac"
itr.hasNext(); // return True
itr.next(); // return "bc"
itr.hasNext(); // return False
class CombinationIterator {
constructor(characters, combinationLength) {
this.combinations = [];
let n = characters.length;
let k = combinationLength;
for (let bitmask = 0; bitmask < (1 << n); bitmask++) {
if (bitmask.toString(2).split('1').length - 1 === k) {
let curr = [];
for (let j = 0; j < n; j++) {
if (bitmask & (1 << (n - j - 1))) {
curr.push(characters[j]);
}
}
this.combinations.push(curr.join(''));
}
}
}
next() {
return this.combinations.pop();
}
hasNext() {
return this.combinations.length > 0;
}
}Input: s = "ab-cd"
Output: "dc-ba"
var reverseOnlyLetters = function(s) {
const letters = s.split('').filter(c => /[a-zA-Z]/.test(c));
letters.reverse();
let idx = 0;
return s.split('').map(c => {
if (/[a-zA-Z]/.test(c)) {
return letters[idx++];
} else {
return c;
}
}).join('');
};Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get "ba", which is equal to goal.
var buddyStrings = function(s, goal) {
if (s.length !== goal.length) return false;
if (s === goal) {
const freq = new Map();
for (const ch of s) {
if (freq.has(ch)) return true;
freq.set(ch, 1);
}
return false;
}
let firstIndex = -1, secondIndex = -1;
for (let i = 0; i < s.length; ++i) {
if (s[i] !== goal[i]) {
if (firstIndex === -1) firstIndex = i;
else if (secondIndex === -1) secondIndex = i;
else return false;
}
}
return secondIndex !== -1 &&
s[firstIndex] === goal[secondIndex] &&
s[secondIndex] === goal[firstIndex];
};