TikTok OA 真题
A robot responds to two commands, U or D, telling it to move one step up (U) or one step down (D) on a vertical line. Given a string commands, after executing all commands in order, determine where the robot stops relative to its starting position:
- Return
"U"if it stops above the starting position. - Return
""if it stops at the starting position. - Return
"D"if it stops below the starting position.
solution("UUDDUD") = "D"
solution("DDUDDDUUU") = ""
Constraints
- 1 ≤
commands.length≤ 1000 - Execution time limit: 3 seconds (Java)
- Memory limit: 1 GB
解法
维护净位移:U 计 +1、D 计 -1,按总和符号返回。单次遍历,时间 O(n)、空间 O(1)。
def solution(commands: str) -> str:
net = 0
for ch in commands:
if ch == 'U':
net += 1
elif ch == 'D':
net -= 1
if net > 0:
return "U"
if net < 0:
return "D"
return ""class Solution {
String solution(String commands) {
int net = 0;
for (int i = 0; i < commands.length(); i++) {
char ch = commands.charAt(i);
if (ch == 'U') net++;
else if (ch == 'D') net--;
}
if (net > 0) return "U";
if (net < 0) return "D";
return "";
}
}class Solution {
public:
string solution(string commands) {
int net = 0;
for (char ch : commands) {
if (ch == 'U') net++;
else if (ch == 'D') net--;
}
if (net > 0) return "U";
if (net < 0) return "D";
return "";
}
};Given a string text, count the number of length-3 substrings that contain exactly 2 vowels (a, e, i, o, u).
solution("welcome") = 2
solution("") = 0
solution("banana") = 2
Constraints
- 0 ≤
text.length≤ 1000 - Execution time limit: 3 seconds (Java)
- Memory limit: 1 GB
解法
长度为 3 的定长滑动窗口。维护窗口内元音数,入窗加、出窗减。时间 O(n)。
def solution(text: str) -> int:
n = len(text)
if n < 3:
return 0
vowels = set("aeiou")
cnt = sum(1 for c in text[:3] if c in vowels)
ans = 1 if cnt == 2 else 0
for i in range(1, n - 2):
if text[i + 2] in vowels:
cnt += 1
if text[i - 1] in vowels:
cnt -= 1
if cnt == 2:
ans += 1
return ansimport java.util.Set;
class Solution {
int solution(String text) {
int n = text.length();
if (n < 3) return 0;
Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u');
int cnt = 0;
for (int i = 0; i < 3; i++) {
if (vowels.contains(text.charAt(i))) cnt++;
}
int ans = (cnt == 2) ? 1 : 0;
for (int i = 1; i <= n - 3; i++) {
if (vowels.contains(text.charAt(i + 2))) cnt++;
if (vowels.contains(text.charAt(i - 1))) cnt--;
if (cnt == 2) ans++;
}
return ans;
}
}class Solution {
bool isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
public:
int solution(string text) {
int n = text.size();
if (n < 3) return 0;
int cnt = 0;
for (int i = 0; i < 3; i++) {
if (isVowel(text[i])) cnt++;
}
int ans = (cnt == 2) ? 1 : 0;
for (int i = 1; i <= n - 3; i++) {
if (isVowel(text[i + 2])) cnt++;
if (isVowel(text[i - 1])) cnt--;
if (cnt == 2) ans++;
}
return ans;
}
};Given an integer n, return an n × n square frame as an array of strings, where the border consists of * characters and the interior is filled with spaces.
solution(8) = [
"********",
"* *",
"* *",
"* *",
"* *",
"* *",
"* *",
"********"
]
solution(2) = [
"**",
"**"
]
Constraints
- 2 ≤
n≤ 100 - Execution time limit: 3 seconds (Java)
- Memory limit: 1 GB
解法
顶行和底行各 n 个星号;中间行为「星号 + (n-2) 空格 + 星号」;拼起来即可。输出规模 O(n²)。
def solution(n: int) -> list[str]:
top_bottom = "*" * n
middle = "*" + " " * (n - 2) + "*"
ans = [top_bottom]
for _ in range(n - 2):
ans.append(middle)
ans.append(top_bottom)
return ansimport java.util.Arrays;
class Solution {
String[] solution(int n) {
char[] topBottom = new char[n];
Arrays.fill(topBottom, '*');
String tb = new String(topBottom);
char[] mid = new char[n];
Arrays.fill(mid, ' ');
mid[0] = '*';
mid[n - 1] = '*';
String m = new String(mid);
String[] ans = new String[n];
ans[0] = tb;
ans[n - 1] = tb;
for (int i = 1; i < n - 1; i++) ans[i] = m;
return ans;
}
}class Solution {
public:
vector<string> solution(int n) {
string topBottom(n, '*');
string mid = "*" + string(n - 2, ' ') + "*";
vector<string> ans;
ans.reserve(n);
ans.push_back(topBottom);
for (int i = 1; i < n - 1; i++) ans.push_back(mid);
ans.push_back(topBottom);
return ans;
}
};Given a sorted array departure_times of past bus departure times (as minutes from a reference epoch) and a current_time, return the number of minutes since the most recent bus departure that is strictly earlier than current_time. If no bus has departed before current_time, return -1.
solution(departure_times = [-12, -10, -8, -6], current_time = -4) = 2
solution(departure_times = [], current_time = -4) = -1
Constraints
- 0 ≤
departure_times.length≤ 100 - 0 ≤
departure_times[i]≤current_time - Execution time limit: 3 seconds (Java)
- Memory limit: 1 GB
Given grid dimensions n × m and an array figures of shape labels from {'A', 'B', 'C', 'D', 'E'}, place each shape on the first available position scanning row by row, left to right. Each cell takes the 1-based index of the figure that occupies it (0 if empty). Return the final grid.
Note: Shape definitions are platform-specific; the code below uses placeholder shapes — replace SHAPES with the actual offsets given in your test.
n = 4, m = 4, figures = ['D', 'B', 'A', 'C']
solution(n, m, figures) =
[[1, 2, 2, 2],
[1, 1, 3, 0],
[1, 4, 4, 0],
[0, 4, 4, 0]]
Constraints
- 2 ≤
n,m≤ 50 - 1 ≤
figures.length≤ 500 - Execution time limit: 3 seconds (Java)
- Memory limit: 1 GB
You are given travelPhotos, a list of pairs [u, v] meaning that location u and v are directly connected by one trip. The trips form a single simple path. Reconstruct and return the ordered list of locations along that path (either direction is accepted).
travelPhotos = [[1, 5], [3, 4], [4, 1], [2, 3]]
solution(travelPhotos) = [5, 1, 4, 3, 2] // or its reverse
Constraints
- 1 ≤
travelPhotos.length≤ 10⁴ travelPhotos[i].length == 2- 1 ≤
travelPhotos[i][j]≤ 10⁵ - Execution time limit: 3 seconds (Java)
- Memory limit: 1 GB
There are two stations Alpha and Beta. Sorted arrays alpha2beta and beta2alpha list departure times from Alpha-to-Beta and Beta-to-Alpha shuttles. Each shuttle takes 100 time units. Starting at time 0 at Alpha, complete missions round trips (Alpha to Beta and back), always taking the earliest available shuttle. Return the final arrival time.
alpha2beta = [0, 200, 500], beta2alpha = [99, 210, 450], missions = 1
solution(alpha2beta, beta2alpha, missions) = 310
alpha2beta = [109, 200, 500], beta2alpha = [99, 210, 600], missions = 2
solution(alpha2beta, beta2alpha, missions) = 700
Constraints
- 1 ≤
alpha2beta.length,beta2alpha.length≤ 100 - 0 ≤
alpha2beta[i],beta2alpha[i]≤ 2000 - 1 ≤
missions≤ 10 - Execution time limit: 3 seconds (Java)
- Memory limit: 1 GB
You are given paragraphs, an array of paragraphs where each paragraph is an array of words, and an integer width. Build a newspaper page: greedily pack words into lines of width at most width, pad each line on the right with spaces to exactly width, wrap with * borders on left/right of each line and a full row of * of length width + 2 before, between, and after paragraphs.
paragraphs = [["hello", "world"], ["how", "are", "you"]], width = 7
solution(paragraphs, width) =
["*********",
"*hello *",
"*world *",
"*********",
"*how are*",
"*you *",
"*********"]
Constraints
- 1 ≤
paragraphs.length≤ 20 - 1 ≤
paragraphs[i].length≤ 10 - 1 ≤
paragraphs[i][j].length≤width - 5 ≤
width≤ 50
Given an array fruits of fruit types and an integer k, count the number of contiguous subarrays such that the number of pairs of identical fruits within the subarray is at least k. A fruit type appearing c times in a subarray contributes c × (c-1) / 2 pairs.
fruits = [0, 1, 0, 1, 0], k = 2
solution(fruits, k) = 3
fruits = [2, 2, 2, 2, 2, 2], k = 3
solution(fruits, k) = 1
Constraints
- 2 ≤
fruits.length≤ 2000 - 0 ≤
fruits[i]≤ 10⁴ - 1 ≤
k≤fruits.length × (fruits.length - 1) / 2
Given a resources array containing characters A and P, and an integer conversionRate, repeatedly perform a cycle that consumes 2 A and conversionRate P, producing 1 A. Return the maximum number of cycles before resources run out.
resources = ['A', 'A', 'A', 'P', 'P', 'P', 'P'], conversionRate = 2
solution(resources, conversionRate) = 3
resources = ['A', 'P'], conversionRate = 2
solution(resources, conversionRate) = 0
Constraints
- 2 ≤
resources.length≤ 500 resources[i]∈{'A', 'P'}- 2 ≤
conversionRate≤ 500
Given an array of non-negative integers a, return the count of elements whose decimal representation contains an odd number of digit 0.
solution([20, 11, 10, 10070, 7]) = 3
Constraints
- 1 ≤
a.length≤ 1000 - 0 ≤
a[i]≤ 10⁸
Given a 2D matrix and an array of commands, apply each command in order and return the resulting matrix. Commands include: swapRows r1 r2, swapColumns c1 c2, reverseRow r, reverseColumn c, rotate90Clockwise.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
commands = ["swapRows 0 2","swapColumns 1 2","reverseRow 0","reverseColumn 2","rotate90Clockwise"]
solution(matrix, commands) = [[1,4,8],[3,6,9],[7,5,2]]
Constraints
- 1 ≤
matrix.length,matrix[i].length≤ 100 - 1 ≤
commands.length≤ 100
Given a string word of lowercase letters and a list skeletons of equal-length strings consisting of - and lowercase letters, return all skeletons that can be transformed into word by replacing each - with some letter taken from the same skeleton (multiset of remaining letters must match word minus the fixed positions).
word = "hello", skeletons = ["he-lo", "he-o", "-ell-", "hello"]
solution(word, skeletons) = ["he-lo", "hello"]
Constraints
- 1 ≤
word.length≤ 100 - 1 ≤
skeletons.length≤ 100 skeletons[i].length == word.length
Given an array structures, in one operation you can add 1 unit to any single element. The target pattern is a strictly stepwise sequence: either ascending (a[i+1] = a[i] + 1) or descending (a[i+1] = a[i] - 1). Return the minimum operations to achieve either pattern.
structures = [1, 4, 3, 2]
solution(structures) = 4 // → [5, 4, 3, 2]
structures = [5, 7, 9, 4, 11]
solution(structures) = 9 // → [7, 8, 9, 10, 11]
Constraints
- 2 ≤
structures.length≤ 10⁵ - 1 ≤
structures[i]≤ 10⁹
Given an array numbers and an integer threshold, return the smallest index i such that numbers[i], numbers[i+1], numbers[i+2] are all strictly greater than threshold. Return -1 if none exists.
numbers = [0, 1, 4, 3, 2, 5], threshold = 1
solution(numbers, threshold) = 2
numbers = [-9, 95, 94, 4, 5], threshold = 42
solution(numbers, threshold) = -1
Constraints
- 3 ≤
numbers.length≤ 1000 - -1000 ≤
numbers[i],threshold≤ 1000
Given a non-negative integer array numbers, repeat: find the leftmost non-zero element x = numbers[i]. Starting from i, subtract x from each element going right; stop when you hit an element strictly less than x (do not subtract) or you go past the end. Add x to the running result. Repeat until all elements are zero. Return the final result.
solution([3, 3, 5, 2, 3]) = 6 // (3) → (2) → (1)
solution([5, 5, 5, 5]) = 5
Constraints
- 1 ≤
numbers.length≤ 100 - 0 ≤
numbers[i]≤ 10⁶
Given a 2D grid bubbles, a bubble at (r, c) is eligible if at least 2 of its 4-directional neighbors share its color. All eligible bubbles plus their same-color neighbors are marked for simultaneous removal, then everything above empty cells falls down by gravity (per column). Return the final grid (empty cells become 0).
bubbles = [[3,1,2,1],
[1,1,1,4],
[3,1,2,2],
[3,3,3,4]]
solution(bubbles) = [[0,0,0,1],
[0,0,0,4],
[0,0,2,2],
[3,0,2,4]]
Constraints
- 1 ≤
bubbles.length,bubbles[0].length≤ 100 - 1 ≤
bubbles[i][j]≤ 10⁴
Given two integer arrays firstArray and secondArray, return the length of the longest decimal prefix common to some pair (a, b) with a from the first array and b from the second. Return 0 if no pair shares any prefix.
firstArray = [25, 288, 2655, 54546, 54, 555], secondArray = [2, 255, 266, 244, 26, 5, 54547]
solution(firstArray, secondArray) = 4
Constraints
- 1 ≤
firstArray.length≤ 5 × 10⁴ - 1 ≤
firstArray[i],secondArray[i]≤ 10⁹
Given an array recording of uppercase and lowercase English letters representing keys pressed (where case does not change the physical key), count the number of times the user switched physical keys.
solution(['W','w','a','A','a','b','B']) = 2
solution(['w','w','a','w','a']) = 3
Constraints
- 1 ≤
recording.length≤ 1000
Given an array departure_times of HH:MM strings (chronologically sorted within a single day) and a current_time string, return the number of minutes since the most recent bus strictly earlier than current_time. Return -1 if none.
departure_times = ["12:30","14:00","19:55"], current_time = "14:30"
solution(departure_times, current_time) = 30
departure_times = ["00:00","14:00","19:55"], current_time = "00:00"
solution(departure_times, current_time) = -1
Constraints
- 3 ≤
departure_times.length≤ 100
Given an initial bit array memory (length divisible by 8) and an array of queries, support: alloc x (find leftmost run of x zeros starting at index divisible by 8, mark it 1, assign next ID; return start index or -1); erase ID (free that block; return length removed, or -1 if invalid). Return per-query results.
memory = [0,1,0,0,0,1,1,0,0,0,0,1,1,1,1]
queries = [[0,2],[0,1],[0,1],[1,1],[0,3],[1,4],[0,4]]
solution(memory, queries) = [8, 0, -1, 2, 8, -1, -1]
Constraints
- 8 ≤
memory.length≤ 320 - 2 ≤
queries.length≤ 300
Given an array of positive integers numbers, count pairs (i, j) with 0 ≤ i < j < numbers.length such that one number can be transformed into the other by swapping at most two of its digits (including the no-swap case if they are already equal).
solution([1, 23, 156, 163, 461, 165, 32]) = 3
solution([123, 321, 123]) = 3
Constraints
- 1 ≤
numbers.length≤ 10⁴ - 1 ≤
numbers[i]≤ 10⁹
Given a string text of space-separated words (mixed case English letters), count words whose first and last letters are the same letter (case insensitive).
solution("Level dEMaND noNe") = 2
solution("") = 0
solution("b Bb aAa") = 3
Constraints
- 0 ≤
text.length≤ 1000
Given forest (an array of positive integers and zeros) and a starting position bird (where forest[bird] = 0), the bird picks up sticks: fly right to find the nearest stick (positive value), bring it back, then alternate direction. Stop when total stick length reaches 100. Return the 1D indices of sticks in the order taken.
forest = [25, 0, 50, 0, 0, 0, 0, 15, 0, 0, 45], bird = 4
solution(forest, bird) = [7, 2, 10]
Constraints
- 3 ≤
forest.length≤ 1000 - 0 ≤
forest[i]≤ 50
Given an n × m grid, an array obstacles of blocked cells, and teleports (pairs of source-to-destination cells), starting at (0, 0) repeatedly try to move right; if that fails, try down; otherwise stop. Teleports trigger instantly when entering a source cell. Return the number of cells visited if you reach (n-1, m-1). Return -1 if blocked, or -2 if stuck in a teleport cycle.
Constraints
- Reasonable grid + lists; per-platform limits apply.
Given an array cityLine of skyscraper heights (each of width 1), return the area of the largest axis-aligned square that fits within the silhouette.
solution([1, 2, 3, 2, 1]) = 4
solution([4, 3, 4]) = 9
Constraints
- 1 ≤
cityLine.length≤ 10⁶ - 1 ≤
cityLine[i]≤ 10⁶
Given a distinct positive integer array heights, a position is a highlight if it is strictly greater than both adjacent neighbors (boundaries count as nonexistent). Repeatedly remove the smallest highlight and append it to the answer until no highlights remain.
heights = [2, 7, 8, 5, 1, 6, 3, 9, 4]
solution(heights) = [6, 8, 7, 5, 2, 9, 4, 3, 1]
Constraints
- 1 ≤
heights.length≤ 100
A matrix mat of shape 4 × (4 × n) consists of n side-by-side 4×4 blocks; each block contains the digits 1–16 exactly once, except one cell is "?". For each block, fill in the missing value, then sort the blocks by missing value (stable on ties). Return the rebuilt matrix.
Constraints
- Per CodeSignal limits.
Given a permutation deck of 1..n from top to bottom, the only allowed operation is to move the top k cards to the bottom (single rotation by k). Find the minimum k such that the rotated deck is [1, 2, ..., n]. Return -1 if impossible.
solution([1, 4, 2, 3]) = -1
solution([3, 4, 5, 1, 2]) = 3
Constraints
- 3 ≤
deck.length≤ 100
Given a 2D integer matrix moistureGrid with values in [0, 255] and a smoothingRadius, replace each cell with floor((cell + mean(neighbors)) / 2), where neighbors are all cells within Chebyshev distance smoothingRadius (excluding the cell itself). If a cell has no neighbors, leave it unchanged. mean is integer-division of sum by count.
Constraints
- 1 ≤ rows, cols ≤ 50
- 0 ≤ values ≤ 255
- 1 ≤
smoothingRadius≤ 5
Given a string word, consider every string formable by reversing exactly one prefix or one suffix of word. Return the lexicographically smallest such result.
solution("dbaca") = "abdca"
Constraints
- Per CodeSignal limits (
O(word.length³)acceptable).
Given an array dataSizes and a non-negative integer threshold, find the maximum length of a contiguous subarray such that sum(subarray) - sum(prefix before subarray) ≤ threshold. Return 0 if none.
dataSizes = [1, 2, 3, 4], threshold = 5
solution(dataSizes, threshold) = 2
dataSizes = [8, 5, 6, 1, 4, 1, 9], threshold = 5
solution(dataSizes, threshold) = 4
Constraints
- 0 ≤
dataSizes.length≤ 10⁵ - 0 ≤
dataSizes[i]≤ 10⁴
Given an array of strings wordsList, return a new array where each word of even length is reversed and each word of odd length is uppercased.
solution(["HeLLo", "Data", "science"]) = ["HELLO", "ataD", "SCIENCE"]
solution([]) = []
Constraints
- 0 ≤
wordsList.length≤ 100 - 1 ≤
wordsList[i].length≤ 50
Given arrays ingredients and recipes (both arrays of strings), for each recipe return whether it equals the concatenation of the first i+1 ingredients (for some i ≥ 0).
ingredients = ["flour","sugar","eggs"]
recipes = ["floursugar","random","flour","sugarflour","sugareggs"]
solution(ingredients, recipes) = [true, false, true, false, false]
Constraints
- Per CodeSignal limits.
A reactor processes one sample at a time, each synthesis taking 300 seconds. Samples arrive at sorted times times. The cooling chamber (waiting room, excluding the active sample) holds at most 10; arrivals when it is full are rejected. Return the time the last accepted sample finishes.
solution([1, 6, 9, 502]) = 1201
solution([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]) = 3601
Constraints
- 1 ≤
times.length≤ 1000 - 0 ≤
times[i]≤ 5 × 10⁴
Given an array readings of non-negative integers, repeatedly replace each element with its digit sum until every value is a single digit (i.e. apply the digital root). Return the most frequent digit in the final array; ties broken by larger digit.
solution([123, 456, 789, 101]) = 6
solution([6]) = 6
solution([3, 12, 23, 32, 0]) = 5
Constraints
- 1 ≤
readings.length≤ 100 - 0 ≤
readings[i]≤ 10⁶
Process a sequence of operations:
["acquisition", category, qty, price]— addqtybooks ofcategoryvalued atprice["checkout", category, qty]— borrowqtybooks ofcategory, cheapest first["reclassify", category, qty, oldPrice, newPrice]— changeqtybooks fromoldPricetonewPrice
Return the total insurance value per checkout, in order.
Constraints
- 1 ≤
operations.length≤ 100
You are given a kanban-style task tracker with four user stories (create, delete, edit, move-status). Manually test by exercising each story and pick up to 2 buggy stories. This is a manual QA prompt and not a coding problem.
The street is the segment [0, finish]. Scooters sit at sorted positions scooters and each scooter, once activated, carries you up to 10 units forward before depleting. Algorithm: from current position, walk to the next scooter to the right, ride 10 units (or to finish if closer), repeat. If no scooter remains, walk the rest. Return total distance traveled on scooters.
solution(23, [7, 4, 14]) = 19
solution(27, [15, 7, 3, 10]) = 20
solution(10, []) = 0
Constraints
- 1 ≤
finish≤ 1000 - 0 ≤
scooters.length≤ 200
Same street model as scooter, but track the on-foot distance (instead of scooter distance). From the current position, walk to the next station ahead; if no station, walk to target. Return the total foot distance.
solution(23, [7, 4, 14]) = 4
Constraints
- Per CodeSignal limits.
You need to use a phone for t minutes. Battery i lasts capacity[i] minutes when full, and after depletion needs recharge[i] minutes before reuse. You start on battery 0; on depletion, cycle to the next available battery (skip those still recharging). Return the count of fully depleted batteries used, or -1 if at some point all batteries are recharging and you cannot continue.
solution(t=16, capacity=[2,5,6], recharge=[12,1,4]) = 3
solution(t=16, capacity=[2,5,6], recharge=[12,8,4]) = -1
Constraints
- 1 ≤
t≤ 5000 - 1 ≤
capacity.length=recharge.length≤ 100
Given integer arrays primary and secondary, process operations of two types: [0, index, newValue] sets secondary[index] = newValue; [1, targetSum] returns the count of pairs (i, j) with primary[i] + secondary[j] = targetSum. Return the results of type-1 queries in order.
primary = [1,2,3], secondary = [3,4], operations = [[1,5],[0,0,1],[1,5]]
solution(primary, secondary, operations) = [2, 1]
Constraints
- Per CodeSignal limits (small enough for
O(n)per query).
Given a binary array state and a list of operations: "L" sets the smallest-index 0 to 1 (no-op if none); "C{index}" sets state[index] = 0. Return the final binary string.
state = [0,0,0,0,0,0,0,0,0,0], operations = ["L","L","C0","L","C3"]
solution(state, operations) = "1100000000"
Constraints
- 1 ≤
state.length≤ 10⁵
Given an array heights and an integer viewingGap, return the minimum |heights[a] - heights[b]| over all pairs (a, b) with |a - b| ≥ viewingGap.
heights = [1,5,4,10,9], viewingGap = 3
solution(heights, viewingGap) = 4
heights = [3,10,5,8], viewingGap = 1
solution(heights, viewingGap) = 2
Constraints
- Per CodeSignal limits.
Given an integer array arr, count contiguous subarrays of length ≥ 1 that alternate between even and odd values (parity differs between adjacent elements).
solution([1,3,5,7,9]) = 5
solution([1,2,1,2,1]) = 15
solution([1,2,3,7,6,5]) = 12
Constraints
- 2 ≤
arr.length≤ 10⁵ - -10⁸ ≤
arr[i]≤ 10⁸
Given an array arr, build an output of length arr.length - 2 where output[i] = 1 if arr[i], arr[i+1], arr[i+2] is strictly increasing or strictly decreasing, else 0.
arr = [1, 2, 1, -4, 5, 10]
solution(arr) = [0, 1, 0, 1]
Constraints
- 3 ≤
arr.length≤ 1000
Given an array of non-negative integers visits and a target, return the smallest index i such that visits[0] + visits[1] + ... + visits[i] ≥ target, or -1 if the total never reaches target.
visits = [200, 300, 150, 250, 800], target = 700
solution(visits, target) = 3
visits = [10, 20, 30, 40], target = 500
solution(visits, target) = -1
Constraints
- Per CodeSignal limits.
Given a string inputString, remove all vowels (a, e, i, o, u, both cases) and reverse the remaining characters.
solution("Hello world") = "dlrw olH"
Constraints
- 0 ≤
inputString.length≤ 1000
You are implementing a simple substitution cipher on a string memo. Every k-th consonant (1-indexed within the running consonant count) is shifted to the next consonant in the alphabet; vowels and non-letters are untouched. Shifting from z wraps to b (case preserved).
Example:
memo = "CodeSignal",k = 3→"CodeTignam". Consonants areC, d, S, g, n, l; the 3rd and 6th (S,l) shift toT,m.memo = "Quiz, Citizenship, puZZle",k = 5→"Quiz, Citizenship, quZZle".
Constraints
- 1 ≤
memo.length≤ 1000 - 1 ≤
k≤ 26
A cross in a matrix is formed by selecting one row and one column. It is regular if all elements in that row and column are equal. It is nearly regular if all of them are equal except possibly the cell at the row-column intersection. Every regular cross also counts as nearly regular. Return the number of nearly regular crosses.
Example:
matrix = [[1,1,1,1],[2,3,1,1],[1,1,1,0],[1,4,1,1]]→2.matrix = [[1,2],[2,1]]→4.matrix = [[2,3]]→2.
Constraints
- 1 ≤
matrix.length, matrix[0].length≤ 50 - 0 ≤
matrix[i][j]≤ 10
A file is transmitted in segments. Each segments[i] = [l, r] represents a 1-based inclusive byte range received in the i-th transmission. After each segment is received, return the total number of unique bytes received so far. Segments can overlap or repeat.
Example:
segments = [[1,1],[2,2],[3,3]]→[1, 2, 3].segments = [[1,1],[2,2],[3,5]]→[1, 2, 5].
Constraints
- 1 ≤
segments.length≤ 10⁵ - 1 ≤
segments[i][0]≤segments[i][1]≤ 10¹⁸
Given an array fragments of positive integers and an integer accessCode, count the number of ordered pairs (i, j) with i != j such that the decimal concatenation of fragments[i] followed by fragments[j] equals accessCode.
Example:
fragments = [1, 212, 12, 12],accessCode = 1212→3. Pairs:(0,1),(2,3),(3,2).fragments = [11, 11, 110],accessCode = 11011→2. Pairs:(2,0),(2,1).fragments = [777, 7, 777, 77, 77],accessCode = 7777→6.
Constraints
- 2 ≤
fragments.length≤ 3 × 10⁴ - 1 ≤
fragments[i]≤ 10⁵
Given target, return the subsequence of elements that are strictly greater than both neighbors. The first and last elements are always included (they only have one neighbor each).
Example:
target = [1, 3, 1, 3, 2]→[1, 3, 3, 2].target = [1, 3, 3, 3]→[1, 3].target = [1, 2, 1]→[1, 2, 1].
Constraints
- 1 ≤
target.length≤ 100 - -100 ≤
target[i]≤ 100
You start with a rating of 1500. The array diffs records each change. After all changes, return [highest_ever, current]. The rating is guaranteed to stay non-negative.
Example:
diffs = [100, -200, 350, 100, -600]→[1850, 1250].diffs = []→[1500, 1500].
Constraints
- 0 ≤
diffs.length≤ 1000 - -1000 ≤
diffs[i]≤ 1000
Distribute numbers into two arrays first and second:
numbers[0]goes tofirst,numbers[1]goes tosecond.- For
i > 1,numbers[i]goes to whichever array currently has more elements strictly greater thannumbers[i]. On tie, the shorter array. Still tied,first.
Return first concatenated with second.
Example:
numbers = [5, 7, 6, 9, 2]→[5, 9, 2, 7, 6].
Constraints
- 2 ≤
numbers.length≤ 10⁴ - 0 ≤
numbers[i]≤ 10⁷
A number line [0, length - 1] starts uncolored (treat as color 0). Each query [coord, color] paints that single coordinate (overwriting). After each query, record the number of adjacent pairs (i, i+1) with the same color (only counting positions that have been painted, so the "0" background does not count — only adjacencies between actually painted equal colors count as same-color pairs).
Example:
length = 7,queries = [[1, 2], [0, 2], [3, 5], [3, 2], [2, 2], [6, 1], [1, 3]]→[0, 1, 1, 1, 3, 3, 1].
Constraints
- 1 ≤
length≤ 10⁹ - 1 ≤
queries.length≤ 10⁵
Given two arrays prices and ratings of positive integers, find the index of the item with the highest rating / price ratio. On tie, return the lowest index.
Example:
prices = [7, 5, 2, 11],ratings = [3, 4, 1, 3]→1(best ratio4/5 = 0.80).prices = [6, 5, 4, 3],ratings = [4, 3, 1, 2]→0(4/6 == 2/3 ≈ 0.66; choose lower index).
Constraints
- 1 ≤
prices.length≤ 100 - 1 ≤
prices[i], ratings[i]≤ 100
The TikTok engineering team is developing a new feature for analyzing viral trends by studying content sequences represented by a string of content of length n consisting of lowercase letters. The team has discovered that to make a video go viral, each character (character) in the content sequence should have an equal frequency.
In one operation, a character can be appended or removed from the content string. Your task is to find the minimum number of operations required to balance the frequency of all characters in the content sequence.
Function Description
Complete the function balanceContent in the editor.
balanceContent has the following parameter:
string content: the original content sequence. Returnsint: the minimum number of operations to balance the content sequence.
Constraints
1 ≤ n ≤ 10⁵The content sequence consists of only lowercase English alphabets
Example 1
Input:
content = "xzyzxa"
Output:
2
Explanation: For the content "xzyzxa", the characters 'z' and 'x' have higher frequencies than others. To balance the frequency of characters, one possible solution is to append one 'a' and one 'y', resulting in content = "xzyzxaya". Alternatively, remove one 'x' and one 'z' would also give a balanced distribution, with the new content sequence content = "xyza". Both approaches result in a valid balanced content sequence, and the minimum number of operations required is 2.
Creating URLs dynamically is a common task when dealing with web applications and APIs. Building these URLs correctly ensures that the desired endpoint is reached with the appropriate parameters.
To build a URL, we define a function buildURL that takes a base URL (baseURL), an endpoint (endpoint), and a list of parameters (params) as a list of key-value pairs. The function concatenates the base URL and endpoint, appends a ? character, and adds the parameters in the format key=value separated by the & character. If the params list contains a page attribute, it should be placed at the end of the URL. Otherwise, the parameters should be built into the URL in the order given in params.
Function Description
Complete the function buildURL in the editor.
buildURL has the following parameters:
-
String baseURL: the base URL
-
String endpoint: the endpoint to be appended to the base URL
-
List> params: a list of key-value pairs representing the parameters Returns String: the complete URL constructed from the inputs
The TikTok team is analyzing clips to measure their unique content strength. Given a string clip of length n consisting of only lowercase English characters, imagine the clip is circular, meaning after the n-th character, the sequence continues from the 1st character again.
Circular Nature: Since the clip is circular, you can form substrings that wrap around from the end of the string back to the beginning. For instance, with the string "yxz", valid substrings include "y","x","z","yx","xz","zy","yxz","xzy" and "zyx".
The "content strength" of a circular clip is determined by the number of unique substrings that consist of only consonants. Your task is to find the content strength of this circular clip.
Function Description
Complete the function calculateContentStrength in the editor.
calculateContentStrength has the following parameter:
string clip: the circular clip whose content strength has to be determined. Returnsint: the content strength of the circular clip
Example 1
Input:
clip = "bac"
Output:
3
Explanation: The different possible substrings of the circular clip are: ["b", "a", "c", "ba", "ac", "cb", "bac", "acb", "cba"]. The substrings that consist of only consonants are: ["b", "c", "cb"].
In ByteDance's vast network of data centers, millions of interconnected servers process content requests, handle user interactions, and deliver data to users globally. Each server is part of a dynamic task execution flow, represented by an array serverTasks, where each entry in the array indicates the next server in the chain that will handle a task.
Optimizing the data pipeline requires careful management of these task handoffs. Once a task is picked up by server i, it triggers a dependency on server serverTasks[i], transferring the load there. However, this data transfer disables both servers i and serverTasks[i] from participating in any further task handoffs, as they are locked due to processing the current load.
Therefore, selecting the right servers and managing the chain reactions of these task handoffs is crucial for maximizing throughput.
Each server at index i points to the next server serverTasks[i], where the task is transferred.
Once this transfer occurs, both the sending server and the receiving server become unavailable for subsequent tasks.
Your challenge is to select servers in such a way that maximizes the overall throughput score.
The throughput score is determined by the sum of the indices of the servers where tasks are successfully handed off.
TASK
Your task is to analyze this network of server-to-server task handoffs, navigate the dependencies, and determine the maximum possible throughput score that can be achieved by optimally choosing the task handoffs.
INPUT
Given the array serverTasks, calculate the maximum throughput score achievable by performing these operations in the most efficient way.
tomtom's note - there are some other examples in the problem source, but they seemed odd, so so I chose not to include them when creating the practice question.
Constraints
1 ≤ n ≤ 2000000 ≤ serverTasks[i] ≤ n
Example 1
Input:
serverTasks = [0, 1, 2]
Output:
3
Explanation: First, we select the server at index 0. It points to itself (server 0), and its throughput is 0. So, the current total throughput is 0. Note that server 0 is now blocked. Next, we select the server at index 1. It points to itself (server 1), and its throughput is 1. So, the current total throughput becomes 0 + 1 = 1. Note that both servers 0 and 1 are now blocked. Then, we select the server at index 2. It points to itself (server 2), and its throughput is 2. So, the current total throughput becomes 0 + 1 + 2 = 3. All servers are now blocked.
Example 2
Input:
serverTasks = [3, 0, 1, 2]
Output:
6
Explanation: The sequence [3, 0, 1, 2] allows for a total throughput score of 6.
Alex is a TikTok influencer who loves shopping online and sharing his latest hauls with his followers. He's super excited about buying several products from an e-commerce website to feature in his next video. Each item on his shopping list has its own price, and Alex wants to show his followers how to get the best deals.
Alex has a number of discount vouchers that he can use on any of his purchases. These vouchers offer a unique discount mechanism: the more vouchers used on a single item, the greater the discount. For instance, for each voucher used on an item, the price of that item is halved. If multiple vouchers are used on the same item, the price is halved repeatedly. The discount can be represented by the following formula:
discounted_price = p/2^k,
where:
p is the original price of the item,
k is the number of vouchers used on that item.
Alex needs to figure out the minimum total cost he'll need to pay to buy all the items he wants while using his vouchers as effectively as possible. Can you help Alex make his followers proud with his savvy shopping skills?
Function Description
Complete the function calculateTikTokShoppingCost in the editor below.
calculateTikTokShoppingCost has the following parameter(s):
int vouchersCount: the number of discount vouchers.int prices[n]: an array representing the prices of the n items Alex wants to buy. Returnsint: the minimum total cost Alex will need to pay to purchase all the items. Constraints1 ≤ prices.length ≤ 10⁵1 ≤ vouchersCount ≤ 10⁵1 ≤ prices[i] ≤ 10⁹
Example 1
Input:
vouchersCount = 3
prices = [8, 2, 13]
Output:
9
Explanation: :)
Given an array of n integers, arr[n], determine all of its subsequences S of three elements and find the validity of arr.
validity = min{3 * abs(mean(S) - median(S)) for all S}
A subsequence is a sequence that can be derived from a sequence by deleting zero or more elements without changing the order of the remaining elements, for example [3, 4] is a subsequence of [5, 3, 2, 4].
Note
mean(A)is the average of the array (the sum of the array divided by the size of the array).median(A)is the middle value of an ordered set of numbers with an odd number of elements.abs(x)is the absolute value of an integer. Function Description Complete the functioncalculateValidityin the editor.calculateValidityhas the following parameters:int arr[n]: the series of integers Returnsint: the validity of the series of integers
Constraints
- 3 ≤ n ≤ 10³
- 1 ≤ arr[i] ≤ 10⁹
- arr contains distinct elements.
Example 1
Input:
arr = [2, 3, 1, 4]
Output:
0
Explanation:
The subsequences of three elements from the array [2, 3, 1, 4] are [2, 3, 1], [2, 3, 4], [2, 1, 4], and [3, 1, 4]. The validity for each subsequence is calculated as follows:
[2, 3, 1]: mean = (2 + 3 + 1) / 3 = 2, median = 2, validity = 3 * |2 - 2| = 0[2, 3, 4]: mean = (2 + 3 + 4) / 3 = 3, median = 3, validity = 3 * |3 - 3| = 0[2, 1, 4]: mean = (2 + 1 + 4) / 3 = 2.33, median = 2, validity = 3 * |2.33 - 2| = 1[3, 1, 4]: mean = (3 + 1 + 4) / 3 = 2.67, median = 3, validity = 3 * |2.67 - 3| = 1 The minimum validity among all subsequences is0.
Example 2
Input:
arr = [1, 2, 4]
Output:
1
Explanation: No explanation for now. Will provide it once find any :D
In the grand finale of a prestigious TikTok tournament, the organizers have prepared several boxes filled with TikTok credits as prizes for the participants. They know exactly how many participants will compete in the tournament and want to ensure that every participant receives an equal number of TikTok credits to avoid any disappointment. The rules of the tournament are strict: once a prize box is opened, all the TikTok credits inside it must be distributed. The organizers need to determine whether they can distribute the TikTok credits in such a way that every participant gets the same number of credits.
Your task is to help the organizers tell the number of possible ways the credits can be distributed equally among all participants. If not possible, return 0.
Function Description
Complete the function canDistributeCredits in the editor.
canDistributeCredits has the following parameters:
int participants: the number of participantsint credits[n]: the number of credits in each box Returnsint: Number of possible ways the credits can be distributed equally among all participants. , A Huge Thank You to the GG of Error-Free Excellence - Spike!༊
Constraints
1 ≤ n ≤ 10⁶1 ≤ participants ≤ 10³1 ≤ credits[i] ≤ 10⁹
Example 1
Input:
participants = 6
credits = [12, 18, 24, 36]
Output:
8
Explanation: To determine if the TikTok credits can be distributed equally among the participants, follow these steps: Total Credits Calculation: Calculate the total number of credits in any possible combination of boxes. Here, we need to check if the sum of any subset of the boxes' credits is divisible by the number of participants (6 in this case). Checking Divisibility:
- Sum of all boxes: 12+18+24+36=90
- Dividing 90 by 6 gives 15 (90 is divisible by 6).
- We need to check smaller combinations to see if the equal distribution is possible:
- Boxes with 12, 18, and 24: 12+18+24=54
- Dividing 54 by 6 gives 9 (54 is divisible by 6).
- Boxes with 12 and 36: 12+36=48
- Dividing 48 by 6 gives 8 (48 is divisible by 6).
- And so on. Conclusion: Since there are 8 combinations where the total number of credits is divisible by the number of participants (6), it is possible to distribute the credits equally.
Example 2
Input:
participants = 5
credits = [7, 3, 6]
Output:
1
Explanation: n/a
ByteDance has launched a new feature on TikTok called "TikTok Collectibles," where users can collect and trade digital cards featuring popular TikTok creators. Each creator has different categories of cards, such as rare cards for the most followed creators, special edition cards with unique designs, and interactive cards that come with exclusive video content.
ByteDance wants to create a number of collectible packs, each containing equal numbers of each type of card. To achieve this, they need to add more cards to ensure each type can be evenly distributed across the packs.
Given the current inventory of each category of cards as an integer array cardTypes of size n, determine the minimum number of additional cards needed so that they can create more than one pack with an equal type distribution.
Function Description
Complete the function cardPackets in the editor.
cardPackets has the following parameter(s):
int cardTypes[n]: the quantity available of card type Returns int: the minimum number of additional cards to add
Constraints
1 ≤ n ≤ 10⁵1 ≤ cardTypes[i] ≤ 500
Example 1
Input:
cardTypes = [4, 7, 5, 11, 15]
Output:
4
Explanation: tomtom's note: '4' is an educated guess. If it is wrong, pls do lmk! You da best! In order to make 2 matching packets, the following numbers of additional cards of each type must be added: [0, 1, 1, 1, 1]. This sums to 4 additional cards. The numbers of cards are [4, 8, 6, 12, 16] and they can be divided evenly among 2 packets. If 3 packets are created, an additional [2, 2, 1, 1, 0] cards are needed, sum = 6 items. This yields quantities [6, 9, 6, 12, 15]. Any number of packets ≥ 2 can be created, but creating 2 packets requires the minimum number of additional cards.
Example 2
Input:
cardTypes = [3, 8, 7, 6, 4]
Output:
2
Explanation: For 2 packets add: [1, 0, 1, 0, 0] (2 cards) to get [4, 8, 8, 6, 4]. For 3 add [0, 1, 2, 0, 2] (5 cards) to get [3, 9, 9, 6, 6]. Any number of packets ≥ 2 can be created, but making 2 packets requires the minimum number of additional cards.
Example 3
Input:
cardTypes = [3, 9, 7, 6, 5, 2]
Output:
4
Explanation: To make 2 packets, add [1, 1, 1, 0, 1, 0] (4 additional cards) to get [4, 10, 8, 6, 6, 4]. For 3 packets, add [0, 0, 2, 0, 1, 1] (4 additional cards) to get [3, 9, 9, 6, 6, 3].
A TikTok user has a username represented by a string of lowercase English letters, username. The user wants to transform their username to explore possible variations. The user can perform the following operations on the username multiple times, in any order:
Replace an occurrence of 'cc' with 'a'.
Replace an occurrence of 'dd' with 'b'.
The user may also choose not to apply any operations, leaving the username unchanged.
Given the string username, determine the total number of distinct usernames that can be generated by applying these transformations. Since the result can be large, return the total count modulo 10⁹+7.
Example 1
Input:
username = "ccc"
Output:
3
Explanation: The possible usernames that can be generated are:
- "ccc" → "ac"
- "ccc" → "ca"
- "ccc" (No operation is applied) Hence the answer is 3.
Starting from position 0, you need to carry cargo to a target position. Along the way there are charging stations at various positions. The process works as follows:
Walk with the cargo to the nearest charging station ahead of your current position.
Use a drone at that station to carry the cargo forward by 10 units (i.e., from station position p to p + 10).
Repeat until the cargo reaches or passes the target.
If no station is ahead, walk the remaining distance on foot.
Compute the total distance you actually carry the cargo on foot (excluding drone-traveled parts).
Approach: Sort the stations. Each round, find the next usable station ahead of your current position, add the walking distance to reach it, then update your position to station + 10. Repeat until reaching or passing the target.
TikTok creates random clips made up of lowercase English letters.
A clip is called "smooth" if the difference between any two letters next to each other is not bigger than a number called diff.
The difference between two letters, x and y, is how far apart they are in the alphabet. For example, the difference between 'a' and 'z' is 25, and between 'f' and 'c' is 3.
i.e. If diff = 3, then the clip "ac" is smooth because the difference between 'a' and 'c' is 2, which is less than or equal to 3. However, the clip "az" is not smooth because the difference between 'a' and 'z' is 25, which is greater than 3.
You are given two numbers: clipLength (the number of letters in the clip) and diff (the maximum allowed difference between two letters next to each other). Your job is to find how many smooth clips of length clipLength can be made. Since the number could be very large, give the answer as the result modulo 10⁹ + 7.
Function Description
Complete the function countBalancedClips in the editor.
countBalancedClips has the following parameters:
-
int clipLength: the length of the clips
-
int diff: the maximum allowed difference between adjacent characters Returnsint: the total number of balanced clips of the given clipLength, modulo (10⁹ + 7)
Constraints
- 2 ≤ clipLength ≤ 10⁵
- 1 ≤ diff ≤ 25
Example 1
Input:
clipLength = 2
diff = 3
Output:
170
Explanation: Consider the following strings of length 2: Produced Word Is Balanced? Remarks "ad" Yes Difference between 'a' and 'd' is 3 i.e ≤ 3 "za" No Difference between 'z' and 'a' is 25 i.e > 3 "zx" Yes Difference between 'z' and 'x' is 2 i.e ≤ 3 "rk" No Difference between 'r' and 'k' is 7 i.e > 3 "yy" Yes Difference between 'y' and 'y' is 0 Other examples of smooth clips for diff = 3 include: "ab", "ac", "df", "zr", and "op". The total number of smooth clips of length 2 for diff = 3 is 170. So, the answer is 170.
TikTok is organizing a grand TikTok event and wants to optimize the content delivery routes for the users. They have numServers servers numbered from 1 to numServers. The servers will be arranged in a sequence as follows: [1, 2, 3, ..., numServers]. The company has a list of numDisconnectedPairs pairs of servers that are not directly connected. Any pair not present in this list are directly connected. A subsegment of the route starting from server start and ending at server end is [start, start+1, start+2, ..., end]. A subsegment of the route is called good when all pairs of servers in that segment are directly connected. TikTok wants to know how many pairs (start, end) there are (1 ≤ start ≤ end ≤ numServers), such that the subsegment starting from server start and ending at server end is good.
Note: Servers can be reused across different subsegments. Each subsegment is considered independently, so a server can be part of multiple "good" subsegments. For example, if a server 3 is part of a "good" subsegment [2, 3, 4], it can still be reused in another "good" subsegment, like [3, 4, 5].
There is a budget and an array of n costs. Repeat the following process until budget is less than the minimum element in cost.
Process
Start at element 0 and work to n - 1.
At each element cost[i]:
If cost[i] If cost[i] > budget, move to the next index. The array is circular, so the next index after n - 1is index 0. Continue until there is not enough budget to make a purchase. Determine how many purchases are made. **Function Description** Complete the functioncountPurchasesin the editor below.countPurchases` has the following parameters:
int cost[n]: the costs of all the itemslong budget: the starting amount of the budget to be spent Returnslong: the number of purchases
Constraints
- 1 ≤ n ≤ 2*10⁵
- 1 ≤ cost[i] ≤ 10⁹
- 1 ≤ budget ≤ 10⁵
Given an integer array, count the number of contiguous subarrays that form a sawtooth sequence — one where adjacent elements have alternating parity (even and odd alternate throughout the subarray).
A single element is also considered a valid sawtooth sequence.
Approach hint: Traverse the array and maintain the current length cur of the alternating sequence ending at each index. If the current and previous elements have different parity, increment cur; otherwise reset cur = 1. Add cur to the result at each step, since it represents the number of valid subarrays ending at the current index.
Example 1
Input:
nums = [1,2,3]
Output:
6
Explanation: All 6 subarrays are valid sawtooth sequences: [1], [2], [3] (single elements), [1,2] (odd→even), [2,3] (even→odd), [1,2,3] (odd→even→odd). Total = 6.
Example 2
Input:
nums = [1,1]
Output:
2
Explanation: [1] and [1] are valid (single elements). [1,1] has the same parity (odd, odd) so it is not a sawtooth sequence. Total = 2.
The TikTok development team is working on a feature to help creators come up with better captions for their videos. TikTok's algorithm favors engaging captions, so you are building an AI tool that paraphrases captions to make them catchier.
However, TikTok charges creators based on the number of characters that get changed after paraphrasing. Therefore, you are tasked with reducing TikTok creators' costs by identifying 'twin-strings' from the captions to avoid paraphrasing the same content multiple times.
Two strings are considered as 'twin-strings' if they are composed of the same characters, regardless of their arrangement or frequency.
For example, "viral" and "rival" are 'twin-strings' since both are composed of the same five characters: 'v', 'i', 'r', 'a', and 'l'. However, "viral" and "trendy" are not 'twin-strings' since they do not share all the same letters.
Given an array of n strings, determine the number of pairs (i, j) such that 0 ≤ i Function Description Complete the function countTwinPairsin the editor.countTwinPairs` has the following parameter(s):
string words[n]: an array ofnstrings Returnslong: the number of valid pairs of 'twin-strings' in the given array.
Constraints
- 1 ≤
n≤ 10⁵ - The sum of the lengths of all strings does not exceed 10⁶
- All strings consist of lowercase English characters only.
Example 1
Input:
words = ["abca", "abaa", "baab", "cba"]
Output:
2
Explanation: Strings "abca" and "cba" are 'twin-strings' because they are made up of the same characters: 'a', 'b' and 'c'. Strings "abaa" and "baab" are 'twin-strings' because they are made up of the same characters: 'a' and 'b'. Thus the pairs (0, 3), (1, 2) are the only valid pairs counted in the answer. Thus the answer is 2.
Example 2
Input:
words = ["apple", "apel", "silent", "listen", "papel"]
Output:
4
Explanation: Note the following case: Strings "apple", "apel" and "papel" are made up of same unique characters: 'a', 'p', 'e' and 'l'. Thus, any pair of them forms a "twin-string". Strings "silent", "listen" are also "twin-string" because they are made up of the same unique characters: 'l', 'i', 's', 't', 'e' and 'n'. Thus, there are 4 such pairs that satisfy the condition 0 ≤ i < j < n and (words[i], words[j]) are "twin-string." Therefore, the answer is 4.
In the competitive world of social media, especially on platforms like TikTok, creators are constantly battling to produce viral content. The stakes are high—every video segment counts. As a data analyst working for TikTok, you've been tasked with a critical mission: to help creators optimize their videos by identifying the most promising segments that could lead to viral success.
Each segment of a TikTok video has an engagement attribute, which reflects its potential to go viral. This attribute is represented as an integer array engagementArray of size 26, corresponding to the letters of the alphabet ('a' to 'z'). Each element in this array is either '1' (indicating a viral segment) or '0' (indicating a non-viral segment).
The goal is to count all possible viral content combinations. A TikTok video is considered viral if the number of non-viral segments in any substring of the video does not exceed a given threshold k. The video is represented by a string of length n.
Given:
A string video of length n.
An integer k, the maximum allowed number of non-viral segments in a viral TikTok video.
An integer array engagementArray of size 26, where each element is either '1' (viral) or '0' (non-viral).
Find the number of unique non-empty substrings of the video that qualify as viral content.
Function Description
Complete the function countViralCombinations in the editor below.
countViralCombinations has the following parameter(s):
string video: A string representing the lineup of TikTok segments, where each character corresponds to a segment's unique attribute or engagement level.
int engagementArray[n]: An array of integers where each element is either '1' (indicating a viral segment) or '0' (indicating a non-viral segment). This array aligns with the English alphabet; for instance, 'a' corresponds to the first element.
int k: An integer denoting the maximum number of non-viral segments allowed in any content formation to consider it viral.
Returns
int: an integer denoting the number of unique content formations that meet the criteria of having no more than k non-viral segments, ensuring each formation is considered viral.
Constraints
1 ≤ n ≤ 1500.1 ≤ k ≤ n.engagementArray[i] ∈ {0, 1}
Example 1
Input:
video = "abc"
engagementArray = [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
k = 2
Output:
6
Explanation: Open to discussion - In the description "int k: An integer denoting the maximum number of non-viral segments allowed in any content formation to consider it viral." means that non-viral should be allowed.
Example 2
Input:
video = "stream"
engagementArray = [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
k = 2
Output:
14
Explanation: n/a
Example 3
Input:
video = "stream"
engagementArray = [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
k = 2
Output:
14
Explanation: n/a
As a data analyst at Trollbox, you've been assigned an innovative project to help maximize creator collaborations for peak viral impact. With so many creators competing for attention, each creator has their own engagement power, which measures how likely they are to boost views, likes, and shares.
Your task is to create collaboration teams where creators join forces to generate ultimate viral content. However, forming these teams follows specific rules:
Creators must be adjacent based on their posting order. This means you can only form teams with creators who post one after the other, without skipping anyone. For example, if creators 1, 2, and 3 post consecutively, they can form a team. However, you cannot combine creators 1, 3, and 5 since they are not adjacent in the posting sequence.
You need at least a minimum number of creators (given by minCreatorsRequired) to form a valid team.
The total engagement power of the creators of the team must meet or exceed a threshold (given by minTotalEngagementPowerRequired) for their collaboration to generate enough buzz to go viral.
Given a list of the creators and their engagement powers, along with the minimum team size and target engagement power, determine the maximum number of collaborations you can create. Remember, each creator can only belong to one collaboration team.
Function Description
Complete the function createMaximumCollaborations in the editor.
createMaximumCollaborations has the following parameter(s):
int creatorsEngagementPower[n]: An array that denotes the engagement power of each creator.int minCreatorsRequired: The minimum number of creators required in a collaboration.int minTotalEngagementPowerRequired: The minimum total engagement power required for a collaboration. Returnsint: The maximum number of collaborations that can be formed from the creators. To Tsoppa’s Burgir ruling the world, one burger at a time!
Constraints
1 ≤ n ≤ 10⁵1 ≤ creatorsEngagementPower[i] ≤ 10⁹1 ≤ minCreatorsRequired ≤ n1 ≤ minTotalEngagementPowerRequired ≤ 10¹⁴
Example 1
Input:
creatorsEngagementPower = [4, 4, 3, 6, 4, 3, 5]
minCreatorsRequired = 2
minTotalEngagementPowerRequired = 8
Output:
3
Explanation: One of the optimal ways to form the collaborations is to first use the first and second creators (4 + 4 = 8). Then, take the third and fourth creators (3 + 6 = 9). Finally, take the fifth, sixth, and seventh creators, with a total engagement power of (4 + 3 + 5 = 12).
Example 2
Input:
creatorsEngagementPower = [5, 4, 3, 2, 1]
minCreatorsRequired = 3
minTotalEngagementPowerRequired = 20
Output:
0
Explanation: No collaboration is possible in this case because the threshold value is greater than the total sum of the engagement powers of all the creators.
Example 3
Input:
creatorsEngagementPower = [4, 6, 8, 11, 9, 12]
minCreatorsRequired = 2
minTotalEngagementPowerRequired = 15
Output:
2
Explanation: There are n = 6 creators. Each collaboration must include at least minCreatorRequired = 2 creators, and the total minTotalEngagementPowerRequired must be equal to 15
- The first collaboration includes the first, second and third creators, with a total engagement power of 4 + 6 + 8 = 18. This is above the minTotalEngagementPowerRequired
- The second collaboration includes the fourth and fifth creators, with a total engagement power of 11 + 9 = 20 Therefore, the max num of collaboration groups that can be formed is so we return
tomtom's note: Not entirely sure if this question is from TikTok, but I included it in the collection just in case :))
There are n candies put from left to right on a table. The candies are numbered from left to right. The i-th candy has weight wi. Alice and Bob eat candies.
Alice can eat any number of candies from the left (she can't skip candies, she eats them in a row).
Bob can eat any number of candies from the right (he can't skip candies, he eats them in a row).
Of course, if Alice ate a candy, Bob can't eat it (and vice versa).
They want to be fair. Their goal is to eat the same total weight of candies. What is the most number of candies they can eat in total?
Example 1
Input:
candies = [1000]
Output:
0
Explanation: There is only one candy, and it is not possible for Alice and Bob to eat the same total weight. So the function should return 0.
Example 2
Input:
candies = [1, 2, 1]
Output:
2
Explanation: Alice takes 1 candy from the left, and Bob takes 1 candy from the right. So the function should return 2.
tomtom's note: Not entirely sure if this question is from TikTok, but I included it in the collection just in case :))
The store has a lot of cups, numbered 1~N on the shelf.
For example, there are 5 cups:
2 1 3 5 4
Ask to pick up 2 cups at a time and swap their positions.
After several times, the serial number of the cups is made:
1 2 3 4 5
For such a simple case, obviously, at least 2 swaps are required to reset.
The input format is two lines:
Line 1:
A positive integer N (N Function Description
Complete the function exchangeCups in the editor below.
exchangeCups has the following parameter(s):
int labels[N]: an array of integers Constraints- N (N
Constraints
N < 10000
ByteDance, renowned for its innovative products like TikTok, is expanding its financial analytics capabilities to offer more comprehensive insights for its creators and partners. The task is to optimize a data processing pipeline for TikTok's financial module platform. The objective is to enhance the analytics to efficiently identify the longest 'good subarray' of financial metrics meeting a specific criterion.
Given an array financialMetrics of size n where each element represents a numerical financial metric, and a threshold value limit, the goal is to find the maximum length of a non-empty consecutive sequence of data points in financialMetrics that satisfies the following condition:
Each data point in the sequence must be greater than limit / the length of the sequence. If there is no termed 'good' subarray of any length, this sequence is termed a subarray in the dataset, the function should return -1.
Function Signature: int findGoodSubarray(int[] financialMetrics, int limit)
Constraints
1 ≤ n ≤ 10⁵1 ≤ financialMetrics[i] ≤ 10⁹1 ≤ limit ≤ 10⁹
Example 1
Input:
financialMetrics = [1, 3, 4, 3, 1]
limit = 6
Output:
3
Explanation: Let's explore them O_o The maximum length of a good subarray is 3 and the good subarray is [3,4,3].
Imagine you're a community manager at TikTok, tasked with building teams for a high-stakes influencer marketing campaign. You have a list of influencers, each with an engagement score based on their recent activity. Your goal is to form the largest squad of influencers who can collaborate seamlessly.
For any team to work well together, the difference between the engagement scores of two consecutive influencers in the squad must be either 0 or 1. If the difference between consecutive influencers is greater than 1, they won't vibe well!
Given the engagement_scores of n influencers, your task is to find the largest possible squad where all members can collaborate smoothly.
Note: You are allowed to rearrange the influencers to maximize team potential!
Function Description
Complete the function findMaxSquadSize in the editor.
findMaxSquadSize has the following parameter:
int[] engagement_scores: an array of integers representing the engagement scores of influencers Returnsint: the size of the largest squad
Constraints
1 ≤ n ≤ 10⁵1 ≤ engagement_scores[i] ≤ 10⁹
Example 1
Input:
engagement_scores = [12, 14, 15, 11, 16]
Output:
3
Explanation: Valid squads of influencers are {11, 12} and {14, 15, 16}. These squads have sizes 2 and 3, respectively, so the largest squad size is 3.
Example 2
Input:
engagement_scores = [1, 13, 2, 3]
Output:
3
Explanation: There are 2 valid squads possible ->> {1, 2, 3} and {13}. These have sizes of 3 and 1, respectively, so the largest squad size is 3 :)
Example 3
Input:
engagement_scores = [10, 10, 10, 10, 11]
Output:
5
Explanation: All the influencers can be in the same squad {10, 10, 10, 10, 11}, so the largest squad size is 5
In a content creator challenge, a user with a bag of balls, each labeled with different numerical values, aims to arrange the balls in a circle to create a video with the highest level of engagement.
Formally, you are provided an array values representing the attributes of each ball. The objective is to arrange these elements in a circle. You have the creative freedom to determine the order in which the elements are positioned in the circle, and you can insert each element at any location within the circle.
The level of engagement for a particular arrangement is calculated as follows:
The first element placed in the circle contributes 0 to the engagement.
For each subsequent element placed, its contribution is equal to the smaller of the numerical values of the elements to its left and right.
The challenge involves finding the arrangement that results in the highest total engagement and producing a TikTok video that captivates the audience.
Function Description
Complete the function findMaximumEngagement in the editor below.
findMaximumEngagement has the following parameters:
int values[n]: an array of integers Returnslong: maximum total engagement that can be achieved overall arrangements
Constraints
- 2 ≤ n ≤ 2*10⁵
There must be some other constrainsts that we haven't found
Given an array of n integers, arr[n], find the value of x that can be applied to the array to minimize the number of inversions. The array can be modified by applying the bitwise XOR to each element of the array with x. The symbol ⊕ means XOR in the example.
An inversion in an array arr is a pair of indices (i, j) where i > j and arr[i] Function Description Complete the function findMinInversionsin the editor below.findMinInversions` has the following parameter:
int arr[n]: the array Returnsint: the minimum possible number of inversions after modifying the array with integerx
Constraints
- 1 ≤ n ≤ 10⁵
- 0 ≤ arr[i]
Example 1
Input:
arr = [8, 5, 2]
Output:
0
Explanation:
See above image
In the first row, after the elements are XORed with 4, there are two inversions.
For [i, j] = [1, 0], and arr[0] = 1 and arr[1] = 12.
For [i, j] = [2, 0], arr[0] = 6 and arr[1] = 12.
For x = 12 the number of inversions is 0. This is the minimum possible, so the answer is 0.
Example 2
Input:
arr = [0, 8, 2, 4]
Output:
1
Explanation:
Given an array of n integers, arr[n], rearrange them so that the following equation is minimized.
Image of this equation is temporarily shown in the following I will find a way to do this
Note: The equation uses 1-based indexing.
Function Description
Complete the function findMinimumSum in the editor below.
findMinimumSum has the following parameters:
int arr[n]: the array to optimize Returns long: the minimum sum of products from the array
Constraints
1 ≤ n ≤ 2 * 10⁵1 ≤ arr[i] ≤ 10⁵
Example 1
Input:
arr = [1, 10, 2, 7, 10, 6, 6]
Output:
127
Explanation:
One of the optimal rearrangements is arr = [10, 1, 7, 6, 6, 2, 10], producing the result 10 * 1 + 1 * 7 + 7 * 6 + 6 * 6 + 6 * 2 + 2 * 10 = 127.
Find the minimum number of changes to make the array consisting of binary numbers with the least number of transitions from 0 -> 1 or 1 -> 0.
Function Description
Complete the function minTransitions in the editor.
minTransitions has the following parameter:
int[] arr: an array of binary integers Returnsint: the minimum number of transitions
Example 1
Input:
arr = [1, 0, 1, 0, 1]
Output:
1
Explanation:
The array can be transformed to [0, 0, 1, 1, 1] after swapping the index 0 and 3, resulting in only one transition from 0 to 1. Alternatively, it can also be transformed to [1, 1, 1, 0, 0] with one transition from 1 to 0. Therefore, the minimum number of transitions is 1.
Imagine you're in charge of TikTok's servers, where millions of videos, comments, and likes are constantly flowing between users. TikTok needs to send these small packets of data across its network to keep users' feeds smooth and up-to-date. However, there's a catch! The TikTok delivery drone, which we'll call TikRouter, can only carry a limited amount of data on each trip between servers.
- Each "like," comment, or part of a video clip is between 1.01 bytes and 3.00 bytes in size.
- TikRouter is responsible for delivering these packets of interactions to TikTok's users but can carry only up to 3.00 bytes per trip.
As the network administrator in charge of TikRouter, your goal is to minimize the number of trips it makes. Each time TikRouter makes a trip, it grabs as many likes, comments, and video snippets as it can without exceeding the 3.00-byte limit. After each delivery, TikRouter returns for more until all packets are delivered.
Your challenge is to design an efficient algorithm that helps TikRouter determine the minimum number of trips required to deliver
npackets of varying sizes. Function Description Complete the functionfindMinimumTripsByTikRouterin the editor below.findMinimumTripsByTikRouterhas the following parameter(s): float packet_sizes[n]: size of the data packets (in bytes) Returnsint: the minimum number of trips required
The question was phrased with verbosity leading
Example 1
Input:
arr = [1, 2, 3, 4, 8, 9]
Output:
4
Explanation: The pair with the maximum GCD in the array [1, 2, 3, 4, 8, 9] is (4, 8), which has a GCD of 4.
Example 2
Input:
arr = [1, 2, 3, 5]
Output:
1
Explanation: The pair with the maximum GCD in the array [1, 2, 3, 5] is (3, 5), which has a GCD of 1.
Given a grid with n rows and m columns, count the number of possible placements for three knights on the grid such that no two knights' placements counter each other. Note that no two knights can be placed in the same cell.
It is known that a knight in chess can counter another piece in cell (a2, b2) from the cell (a1, y1) if either (|a1 - a2| = 1 and |b1 - b2| = 2), or (|a1 - a2| = 2 and |b1 - b2| = 1).
Find the number of possible placements for the three knights on the grid such that no two knights can counter each other.
Constraints
Unknown myth for now (As always, will add once find out)
Example 1
Input:
n = 2
m = 3
Output:
20
Explanation: There are 20 possible placements for the three knights. (That is all for now)
Given multiple paragraphs, their alignment (LEFT or RIGHT), and a maximum line width, format the text like a newspaper: pack words greedily into lines, pad spaces according to alignment, and add a border of * around the entire output.
Rules:
For each paragraph, pack as many words as possible into each line without exceeding width (greedy, using two pointers).
If alignment is LEFT: pad trailing spaces so each line is exactly width characters.
If alignment is RIGHT: pad leading spaces so each line is exactly width characters.
Wrap all lines with a * border: one * on each side of every content line, plus a full row of * characters on the top and bottom. The total line width (including border characters) is width + 2.
Return the formatted output as a list of strings.
Example 1
Input:
paragraphs = ["abc"]
alignments = ["LEFT"]
width = 3
Output:
["*****","*abc*","*****"]
Explanation: width=3, border line = "*****" (width+2=5 stars). The single word "abc" fills the line exactly. With LEFT alignment no extra padding is needed. Output: top border, content line "abc", bottom border.
Example 2
Input:
paragraphs = ["hello world"]
alignments = ["LEFT"]
width = 7
Output:
["*********","*hello *","*world *","*********"]
Explanation: width=7, border line = "*********" (9 stars). "hello" (5) + " world" would exceed 7, so they wrap to separate lines. Each is LEFT-padded with trailing spaces to fill 7 chars: "hello " and "world ". Content lines become "*hello *" and "*world *".
The other quesiton in the same batch was posted on our Discord server oa-update channel.
The TikTok Content creator's videos receives feedback from viewers over time, represented as a binary string, videoFeedback:
1 indicates positive reactions(likes, shares, or comments).
0 indicates negative reactions(skips or dislikes).
The creator wants to improve a video's overall positive reception by strategically targeting a portion of the video for editing or improvement. Here's the strategy:
Choose one specific segment of the video(interval [i, j]) to leave unchanged, where i > 0 and j Outside this segment, the plan is to completely change the content—flipping negative reactions to positive(0 to 1) and positive reactions to negative(1 to 0).
The objective is to maximize the total positive feedback(1s) for the entire video after performing this operation.
Note: The operation must be performed only once.
Function Description
Complete the function getMaxPositiveFeedback in the editor.
getMaxPositiveFeedback has the following parameter:
- string videoFeedback: a binary string representing the feedback on a video, where 1 represents positive feedback and 0 represents negative reaction
Given an array videoScores, of length n, representing the current relevance scores of videos in the recommendation system (i.e., how much a video matches the user's interests, with higher values indicating better matches), the task is to adjust the scores to make all the videos no longer recommended (i.e., reduce all the scores to 0 or below).
Each adjustment decreases one of the video scores by a fixed integer value x. The task is to find the minimum value of x such that after performing at most maxAdjustments adjustments, all the relevance scores will become non-positive (i.e., less than or equal to zero).
Function Description
Complete the function getMinAdjustments in the editor.
getMinAdjustments takes the following parameter:
int videoScores[n]: the current relevance scores of videos in the recommendation systemint maxAdjustments: the maximum number of adjustments allowed Returnsint: the minimum possible integerxrequired
Constraints
1 ≤ n ≤ 10⁵1 ≤ videoScores[i] ≤ 10⁹n ≤ maxAdjustments ≤ 10⁹
Example 1
Input:
videoScores = [1, 2, 3]
maxAdjustments = 4
Output:
2
Explanation:
If x = 1, elements can be decreased by 1 in an operation and it would take a total of 6 adjustments to make all the elements non-positive which exceeds the maxAdjustments allowed.
If the chosen x = 2, then:
- In the first operation, we decrease the first element. The array becomes [-1, 2, 3]
- In the second operation, we decrease the second element. The array becomes [-1, 0, 3]
- In the third operation, we decrease the third element. The array becomes [-1, 0, 1]
- In the fourth operation, we decrease the third element again. The array becomes [-1, 0, -1]
Hence,
x = 2is the minimum possible integer respecting the given conditions. Thus, the answer is 2.
Alex is a TikTok influencer who loves shopping online and sharing his latest hauls with his followers. He's super excited about buying several products from an e-commerce website to feature in his next video. Each item on his shopping list has its own price, and Alex wants to show his followers how to get the best deals.
Alex has a number of discount vouchers that he can use on any of his purchases. These vouchers offer a unique discount mechanism: the more vouchers used on a single item, the greater the discount. For instance, for each voucher used on an item, the price of that item is halved. If multiple vouchers are used on the same item, the price is halved repeatedly.
The discount can be represented by the following formula:
discounted price = p / 2^k
where:
p is the original price of the item.
k is the number of vouchers used on that item.
Function Description
Complete the function getMinimumCost in the editor.
getMinimumCost has the following parameters:
-
int vouchersCount: the number of discount vouchers
-
int[] prices: an array of integers representing the prices of the items Returnsintint: the minimum cost after applying the vouchers
Alex is a TikTok influencer who loves shopping online and sharing his latest hauls with his followers. He's super excited about buying several products from an e-commerce website to feature in his next video. Each item on his shopping list has its own price, and Alex wants to show his followers how to get the best deals.
Alex has a number of discount vouchers that he can use on any of his purchases. These vouchers offer a unique discount mechanism: the more vouchers used on a single item, the greater the discount. For instance, for each voucher used on an item, the price of that item is halved. If multiple vouchers are used on the same item, the price is halved repeatedly. The discount can be represented by the following formula:
discounted_price = p / 2 ^ k.
where:
pis the original price of the item,kis the number of vouchers used on that item. Alex needs to figure out the minimum total cost he'll need to pay to buy all the items he wants while using his vouchers as effectively as possible. Can you help Alex make his followers proud with his savvy shopping skills? Function Description Complete the functiongetMinimumTotalCostin the editor.getMinimumTotalCosthas the following parameters:-
int vouchersCount: the number of discount vouchers
-
int[] prices: an array of integers representing the prices of the items Returnsint: the minimum total cost
91Mini
In the bustling world of TikTok, data management behind the scenes is critical for smooth content delivery. The platform's core storage mechanism is represented by a binary array called tiktokStorage, which holds n bits of data, each representing a different type of content:
Standard content (represented by 0s)
Priority content (represented by 1s)
As TikTok's user engagement peaks, it's essential to minimize the transitions between standard and priority content in tiktokStorage to ensure the platform's content pipeline operates seamlessly.
Two engineers, Liora and Thorne, are tasked with reorganizing the content to achieve this goal. They can perform operations to swap the bits at any two distinct indices in the array.
Your task is to determine the minimum number of swap operations required so that after performing these operations, there are the fewest possible transitions between 0s and 1s in the tiktokStorage array.
Function Description
Complete the function GetOptimalContentStorage in the editor.
GetOptimalContentStorage has the following parameter(s):
int tiktokStorage[n]: An integer array representing the current organization of TikTok's content storage, with 0s for standard content and 1s for priority content.
Constraints
2 ≤ n ≤ 10⁵tiktokStorage[i] ∈ {0, 1}
Example 1
Input:
tiktokStorage = [1, 0, 1, 0, 1]
Output:
1
Explanation: The optimal strategy of operations is to:
- Swap
tiktokStorage[0]andtiktokStorage[3]. After performing this operation, the array becomes[0, 0, 1, 1, 1]. - This configuration of
tiktokStoragehas only one transition between 0s and 1s at index 1 and 2. - It can be proven that no other configuration has fewer transitions than 1.
- Thus, the minimum number of swap operations required to achieve this configuration is 1.
TikTok's influencer network can be represented as a tree of g_nodes numbered from 1 to g_nodes. Each connection between influencers is represented by an edge in the tree, where the i-th edge connects the influencers g_from[i] and g_to[i].
Suppose the maximum distance, i.e., the number of connections between any two influencers, is mx. An influencer is considered primary if they lie on the simple path between two influencers u and v such that the distance between u and v is equal to mx. All other influencers are secondary.
Your task is to find the sum of indices of all the secondary influencers.
Function Description
Complete the function getSecondaryInfluencerSum in the editor.
getSecondaryInfluencerSum has the following parameters:
int g_nodes: the number of influencers in the network.int g_from[g_edges]: one influencer in each connection.int g_to[g_edges]: the other influencer in each connection. Returnslong int: the sum of indices of the secondary influencers.
Constraints
- 2 ≤ g_nodes ≤ 10⁵
- 1 ≤ g_from[i], g_to[i] ≤ g_nodes
- g_edges = g_nodes - 1
- It is guaranteed that the edges from a tree
Example 1
Input:
g_nodes = 4
g_from = [1, 1, 2]
g_to = [2, 3, 4]
Output:
0
Explanation: The maximum distance between any two influencers is 3, the pair (3, 4). All the influencers on the path 3 --> 1 --> 2 --> 4 are primary. Since no influencer is secondary, the answer is 0.
Example 2
Input:
g_nodes = 6
g_from = [1, 1, 1, 2, 3]
g_to = [2, 3, 4, 5, 6]
Output:
4
Explanation: The max distance between any two influencer is 4 for the pair (5, 6). The influeners on the path 5 -> 2 -> 1 -> 3 -> 6 are primary. The only secondary influencer is number 4 :)
Example 3
Input:
g_nodes = 5
g_from = [1, 1, 2, 2]
g_to = [2, 3, 4, 5]
Output:
0
Explanation:
Implement a prototype of a round-robin load-balancing algorithm.
There are n servers indexed from 1 to n, and m requests to be processed. The i^th request arrives at time arrival[i] and takes burstTime[i] time to execute. The load balancer assigns the i^th request to the server with the minimum index. A server that is assigned the i^th request is unavailable from arrival[i] to arrival[i] + burstTime[i]. At arrival[i] + burstTime[i], the server is available to serve a new request.
Given n, arrival, and burstTime for each request, find the index of the server that executes it. If no server is available at the time, the request is dropped, and -1 is reported. If multiple requests arrive at the same time, the one with the smaller index is assigned first.
Function Description
Complete the function getServerIndex in the editor.
getServerIndex has the following parameter(s):
int n: the number of serversint arrival[m]: the arrival time of requestsint burstTime[m]: the burst time of requests Returnsint[m]: the Index of the servers the requests are assigned to, or-1if no server is available
Constraints
1 ≤ n ≤ 10⁵1 ≤ m ≤ 10⁵1 ≤ arrival[i] ≤ 10⁹1 ≤ burstTime[i] ≤ 10⁹
TikTok Content Moderation Team is working to help creators manage their video comments effectively, ensuring a positive environment by identifying spammy behavior in the comments section.
You have a total of n videos and k keywords that you want to monitor for spammy behavior in the comments. The comments are collected in an array called comments, while the keywords that indicate spammy behavior are stored in another array called spam_keywords.
A comment is flagged as spam if it contains at least two instances of the keywords in the spam_keywords array.
Your task is to analyze the comments for each video and return an array of n strings, labeling each comment as either "spam" or "not_spam" based on the presence of the keywords.
Note: If a keyword appears multiple times in a comment, each occurrence counts toward the spam threshold. Also note that, keyword matching should be case-insensitive.
Function Description
Complete the function getSpamComments in the editor.
getSpamComments takes the following arguments:
-
string comments[n]: an array of strings representing comments on TikTok videos
-
string spam_keywords[n]: an array of strings containing keywords that signify spammy behavior Returnsstring[n]: the results of spam detection
Constraints
- 1 ≤ n ≤ 10³
- 1 ≤ k ≤ 10⁵
- 1 ≤ |comments[i]| ≤ 10⁵
- 1 ≤ |spam_keywords[i]| ≤ 10⁵
- It is guaranteed that the sentences and search words consist of lowercase and uppercase English letters and spaces only.
Example 1
Input:
comments = ["viral tricks to boost", "Great viral tips", "boost views and go viral"]
spam_keywords = ["viral", "boost"]
Output:
["spam", "not_spam", "spam"]
Explanation: Hence the answer is ["spam", "not_spam", "spam"].
Example 2
Input:
comments = ["The sun is bright", "Blockbuster bonanza"]
spam_keywords = ["bright", "bonanza", "paid"]
Output:
["not_spam", "not_spam"]
Explanation: The first comment contains only one spam_keyword "bright". The second comment also contains only a single spam_keyword "bonanza". Since both these comments contains only 1 spam_keyword therefore both are flagged as "not_spam". Hence the answer is ["not_spam", "not_spam"].
In the dynamic landscape of TikTok, creators are in a constant race to boost their videos' engagement by leveraging new features that enhance their content.
Each creator starts with a set of m videos, represented by initialReelImpacts, which indicates the baseline popularity of each reel. For the next n days, TikTok releases new trending features, represented by newReelImpacts, with each feature offering an additional boost to the creator's existing reels.
PROCESS FOR EACH DAY:
The creator appends the new feature from newReelImpacts[i] (where 0 ≤ i The updated lineup of reels is reviewed, and the k-th most impactful reel is selected based on its popularity. The impact value of this reel is added to the total impact score. NOTE: The initial impact score of the creator is the k-th highest impact value from the initial set of initialReelImpacts. FUNCTION DESCRIPTION Complete the function getTotalImpact` in the editor below.
PARAMETERS:
int initialReelImpacts[m]: The impact of initialmreels.int newReelImpacts[n]: The impact of the newnreels that appear one by one.int k: The fixed choice made by the creator, representing the position of the most impactful reel selected. RETURNS: long: The total impact achieved by the creator after incorporating all elements fromnewReelImpacts.
Constraints
- 1 ≤ n, m ≤ 10⁵
- 1 ≤ k ≤ m
- 1 ≤ initialReelImpacts[i], neReelImpacts[i] ≤ 10⁹
Example 1
Input:
initialReelImpacts = [2, 3]
newReelImpacts = [4, 5, 1]
k = 2
Output:
13
Explanation: The initial impact score is the 2nd highest value in initialReelImpacts = [2, 3]. Impact score = 2 Over the next n days: Day 1: Append 4. Current reels: [2, 3, 4]. The 2nd highest impact is 3. Impact score = 2 + 3 = 5 Day 2: Append 5. Current reels: [2, 3, 4, 5]. The 2nd highest impact is 4. Impact score = 5 + 4 = 9 Day 3: Append 1. Current reels: [1, 2, 3, 4, 5]. The 2nd highest impact is 4. Impact score = 9 + 4 = 13
Develop a session-based authentication system where each user session generates a new token with a specified time-to-live (TTL) expiration. The TTL expiration is calculated as the current time plus the time-to-live seconds. If a token is renewed, the TTL is extended to the time-to-live seconds after the time of the renewal.
There are three types of queries in this system:
"generate <token_id> <current_time>": Creates a new token with the given token_id and current_time.
"renew <token_id> <current_time>": Renews an unexpired token with the given token_id and current_time. If there is no unexpired token with the specified token_id, the request is ignored.
"count <current_time>": Returns the number of unexpired tokens at the given current_time.
Note: If a token expires at a specific time and any action is performed at that same time, the token's expiration occurs before any other actions are carried out.
Function Description
Complete the function getUnexpiredTokens in the editor below.
getUnexpiredTokens has the following parameter(s):
-
int time_to_live: the time to live for a token
-
String[] queries: the queries Returnsint[]: the results from type-3 query in the same order it is given
Constraints
Unknwon for now
You are given a sequence of n TikTok videos, each represented by a unique rating in the array videoRatings, reflecting the order in which the videos are presented to the user.
A sequence of videos is considered coherent if:
By removing at most one video from the sequence, the remaining videoRatings forms an increasing order.
The TikTok algorithm aims to suggest a coherent sequence to the user by potentially removing some videos, effectively selecting a subsequence of the original sequence.
Given the array videoRatings of length n, determine the minimum number of videos that must be discarded so that the remaining sequence is coherent.
Note: A subsequence is a sequence derived from another sequence by deleting some or no elements, without changing the order of the remaining elements.
There is an array of n integers, arr, and two integers mn and mx.
For each of arr's subarrays, find the binary value of the bitwise OR of all elements. If the number of 1 bits is between mn and mx, inclusive, it's a good subarray.
Determine the length of the longest good subarray.
Note: A subarray is any segment of adjacent elements in an array. For example, if arr = [1, 2, 3], [1, 2] is a subarray but [1, 3] is not.
Function Description
Complete the function longestGoodSubarray in the editor.
longestGoodSubarray has the following parameters:
int arr[n]: an array of integersint mn: an integerint mx: an integer Returnsint: the length of the longest good subarray
Constraints
Unknown so far. If you happen to know about it, feel free to contact Groot in our server. TYVM!
Example 1
Input:
arr = [0, 3, 4, 1, 5]
mn = 1
mx = 2
Output:
3
Explanation: No explanation is provided for now. And I am not 100% sure about the output of this example. If you find it wrong, you are very welcome to let me know, and I will fix it right away. Many many thanks in advance! Cheers, Groot
Implement a fixed-capacity LRU cache that also supports per-entry TTL expiration.
You are given the cache capacity, an array of operation names, and a parallel array of integer arguments. Process the operations in order and return one output string for each get operation.
Each operation has a timestamp as its first argument. Timestamps are non-decreasing.
put has arguments [time, key, value, ttl]. It inserts or updates key with value. The key expires at absolute time time + ttl. Updating an existing key replaces both its value and expiration time. A successful put makes the key most recently used.
get has arguments [time, key]. If the key exists and has not expired, return its value as a string and make the key most recently used. Otherwise, return "-1".
Before processing each operation, remove every expired key. A key is expired when current time ≥ expiration time.
If a put causes the cache to exceed capacity after expired keys have been removed, evict the least recently used remaining key.
Function Description
Complete solveLRUCacheTTL. It has the following parameters:
int capacity: the maximum number of live keys in the cache
String[] operations: each value is either "put" or "get"
int[][] arguments: arguments for each operation, using the formats above
Return a String[] containing the outputs of all get operations in order.
Constraints
1 ≤ capacity ≤ 10⁵
1 ≤ operations.length == arguments.length ≤ 10⁵
operations[i] is either "put" or "get"
For put, arguments[i] has length 4: [time, key, value, ttl]
For get, arguments[i] has length 2: [time, key]
Timestamps are non-decreasing and all TTL values are positive.
Use an O(operations.length) or O(operations.length log operations.length) approach.
Example 1
Input:
capacity = 2
operations = ["put","put","get","put","get","get","get"]
arguments = [[0,1,10,5],[1,2,20,10],[2,1],[6,3,30,5],[6,1],[7,2],[12,3]]
Output:
["10","-1","20","-1"]
Explanation: Key 1 expires at time 5, so it is gone before the operation at time 6. Keys 2 and 3 expire at time 11, so the final get at time 12 misses.
Example 2
Input:
capacity = 1
operations = ["put","put","get","put","get"]
arguments = [[0,5,7,3],[2,5,9,10],[4,5],[5,6,1,10],[6,5]]
Output:
["9","-1"]
Explanation: The second put updates key 5 and extends its expiration. Later, inserting key 6 into a capacity-1 cache evicts key 5.
Several TT creators are participating in a trending challenge called Match-and-Swipe. There are k creators, labeled from 1 to k, and they start with a shared video sequence represented by the string videoSequence. Here is how the challenge works: each creator takes turns (creator 1 goes first, followed by creator 2, and so on, cycling back to creator 1 after cretor k's turn). On each turn, a creator can remove any two consecutive matching clips (represented by matching letters in videoSequence) and merge the remaining parts of the sequence back together. The game continues until there are no consecutive matching clips left. If a creator cannot make a move, they lose, and the challenge ends. Given that all creators play stratigically, determine the number of the creator who will lose.
Example 1
Input:
videoSequence = "pzwoowz"
k = 3
Output:
1
Explanation: Creator videoSequence 1 pzwoowz 2 pzwwz 3 pzz 4 p On each turn, the creator selects the highlighted pair. Creator 1 loses when there are no valid pairs left to remove. Return 1.
A concave subsequence is a subsequence where the first and last elements are greater than all other elements in between. For example, [100, 0, 25, 11, 200] is concave, while [100, 0, 110, 200] is not since the third element is greater than the first element.
Given an array that contains a permutation of n integers, arr[n], determine the length of the longest concave subsequence.
A permutation is a sequence of integers from 1 to n that contains each number exactly once. For example [1, 3, 2] is a permutation while [1, 2, 1] and [1, 2, 4] are not.
A subsequence is derived from a sequence by deleting zero or more elements without changing the order of the remaining elements. For example [3, 4] is a subsequence of [5, 3, 2, 4], but [4, 3] is not.
Function Description
Complete the function maxLength in the editor.
maxLength has the following parameter:
int arr[n]: the array Returns int: the length of the longest subsequence having the required property
Constraints
1 ≤ n ≤ 10⁵1 ≤ arr[i] ≤ narris a permutation of integers from1ton.
102Max Likes
You are a TT content creator with predictions about which trends will be popular over the next n days. These trends are represented by an array prediction, where the trend that will be popular on the i-th day is given by prediction[i]. Before the trends gain popularity, you need to select a set of trends to focus on. For each trend x that you choose, you will earn x likes each time that trend appears in the prediction array. However,to maintain diversity in your content, if you choose the x-th trend, you cannot choose the (x-1)-th or (x+1)-th trends, as they are considered too similar. Your objective is to maximize the number of likes you can earn by carefully selecting which trends to focus on. Since the number of like can be large, return your answer modulo 10⁹ + 7.
Example 1
Input:
prediction = [1, 3, 2]
Output:
4
Explanation: Choose trends 1 and 3. You will get 1 like on the first day and 3 likes on the second day. The total number of likes is 4.
You are given an array called Rates, where rates[i] represents the currency price on the ith day.
You are also given an array called Strategy, where strategy[i] represents an operation. Each operation could be -1 for buy, 0 for hold, and 1 for sell.
You are also given k, which is guaranteed to be an even integer.
You can change the Strategy array like so:
Choose a range of k consecutive elements.
Set the first half of this range to 0.
Set the second half to 1.
Choose an optimal range to change the Strategy array so as to maximize the profit from executing the strategy. Return this maximum profit.
The profit is defined as the sum of all selling rates minus the sum of all buying rates. For example, if rates = [2, 3, 4, 5] and strategy = [1, 0, 0, -1], then your total profit would be (2 * 1) + (5 * -1) = -3.
Example 1
Input:
strategy = [2, 3, 4, 5]
rates = [1, 0, 0, -1]
k = 4
Output:
-3
Explanation: Note - k value in this example is temperorily missing. I will add it once find reliable source :) Your total profit would be (2 * 1) + (5 * -1) = -3
In the dynamic world of TikTok, each user has a list of favorite content categories they are interested in. You are tasked with analyzing the connections between these users, focusing specifically on the number of shared interests. The goal is to determine the highest number of common interests that any pair of TikTok users shares, where the number of common interests is the largest positive integer that evenly divides the number of interests of both users.
You are given an array favoriteCategories of length n where each element represents the number of favorite content categories of a TikTok user. Find the highest number of common interests between any two TikTok users in the network.
Function Description
Complete the function maxSharedCategories in the editor.
maxSharedCategories has the following parameter(s):
int favoriteCategories[n]: an array where each element represents the number of favorite content categories of a TikTok user. Returnsint: the highest number of common interests between any pair of users in the network. Introduce our top-tier GG of Error-Free Excellece --> spike !!
Constraints
2 ≤ n ≤ 10⁴.1 ≤ favoriteCategories[i] ≤ 10⁴
Example 1
Input:
favoriteCategories = [4, 2, 6, 8]
Output:
4
Explanation: Out of all the pairs possible from the array, the maximum number of common interests (the largest positive integer that evenly divides the number of favorite content categories of both users) is between the users with 4 and 8 favorite content categories. The number of common interests is 4, which is the highest possible value.
Example 2
Input:
favoriteCategories = [3, 2, 5]
Output:
1
Explanation: The maximum possible number of common interests between any pairs of TikTok users from the array is 1 since all the pairs of users have favorite categories that are relatively prime (no common interests other than 1).
Example 3
Input:
favoriteCategories = [4, 8, 2, 16]
Output:
8
Explanation: Educated guess: The highest number of common interests between any pair of users in the network.
The TikTok video content analyzer, which is always eager to get the highest views, faced a unique task that required pure coding. The task provided the students with a series of video clips and posed a question based on the content in these clips. Each question involved two missions: to determine the maximum number of views and the students must find an algorithm that determines the maximum number of video views while still showing the most successful creators.
The student's task is to calculate, for each question, the maximum number of video segments that can create the highest engagement. In no valid case will be 0, as possible, the answer should be the maximum number of views that can be achieved by showing clips from the most successful creators.
Function Description
Complete the function maxShownSegments in the editor below.
maxShownSegments has the following parameters:
int arr[n]: an array representing the lengths of video clipsint k: a threshold to determine how many partitions of video segments are allowed
A TikTok participant is engaging in a challenge where they have a binary string representing a sequence of dance moves. The string consists of 0s and 1s, with 0s signifying pauses and 1s representing dance moves.
The participant can choose exactly k distinct positions in the string to modify. These modifications involve flipping the moves at those positions, converting 0s to 1s and 1s to 0s.
The objective is to maximize the count of pairs of consecutive dance moves (1s) in the final dance sequence. In TikTok challenges, participants aim to create the smoothest dance transitions.
Your task is to assist the participant in determining the maximum possible number of pairs of consecutive dance moves (1s) in the final dance sequence after the allowable adjustments.
Note that the count of pairs of consecutive 1s represents the number of indices i (1 ≤ i < n) where s[i] = '1' and s[i+1] = '1', showcasing the seamless dance transitions in the challenge.
Constraints
Unkwnon for now
Example 1
Input:
s = "01010"
k = 2
Output:
3
Explanation:
Following are some possible selection of positions in s:
If we choose 1^st and 3^rd indices, then we get the resulting string as "11110" having 3 pairs of consecutive 1s, which is the maximum possible. Hence, the answer is 3.
In a futuristic TikTok research facility, engineers have discovered a mysterious algorithmic manuscript within the app that promises to revolutionize content creation and engagement for creators worldwide. This manuscript contains a sequence of numbers, represented as an array named efficiencyScores, which includes the efficiency scores of various TikTok tasks. These tasks can be highly efficient, neutral, or even counterproductive. The number of tasks is denoted by n. The manuscript has become the focal point of intense research, as it is believed to hold the key to unlocking unprecedented levels of audience engagement.
Your mission is to assist the engineers in their quest. According to the manuscript, by selecting exactly five tasks in a specific combination that maximizes the overall efficiency, the secret formula for viral content will be revealed.
Your goal is to identify this combination of five tasks that results in the highest possible product, thereby unlocking the potential hidden within the manuscript and advancing content creation science.
Formula:
maximum_product = max(efficiencyScores[i1] * efficiencyScores[i2] * efficiencyScores[i3] * efficiencyScores[i4] * efficiencyScores[i5])
Function Description
Complete the function maximizeEfficiencyProduct in the editor below.
maximizeEfficiencyProduct has the following parameter(s):
int efficiencyScores[n]: the efficiency scores of various tasks. Returnsint: the highest possible product of any five selected efficiency scores.
Constraints
- 5 ≤ n ≤ 10⁵.
- -10³ ≤ efficiencyScores[i] ≤ 10³
Example 1
Input:
efficiencyScores = [6, 1, 2, 8, 1]
Output:
96
Explanation: There are only 5 numbers in the array, we select all of them, and the product is 96.
You are a data analyst at the popular social media company TikTok. Your task is to optimize user engagement on TikTok-like video reels by developing an "engagement boost" algorithm that increases user interaction on the platform.
You are provided with two datasets: views and likes, both of the same length, where each entry represents the views and likes on a particular video. The objective is to maximize the "engagement score," defined as the sum of all likes[i] where likes[i] exceeds views[i].
However, there's a catch! You are allowed to rearrange the likes dataset to maximize the engagement score, but the views dataset remains fixed. Your challenge is to design an efficient algorithm that rearranges the likes dataset to achieve the highest possible engagement score, while adhering to the constraint that the views dataset cannot be rearranged.
Given two arrays of integers, views and likes, your goal is to rearrange the elements of likes to maximize the engagement score.
Function Description
Complete the function maximizeEngagement in the editor.
maximizeEngagement has the following parameters:
-
int[] views: an array of integers representing the views
-
int[] likes: an array of integers representing the likes Returnsint: the maximum engagement score 𓂃 𓈒𓏸 𓆝 𓆟 𓆞 𓂃 𓈒𓏸Couldn’t have done it without A𓂃
Constraints
1 ≤ n ≤ 2 * 10⁵1 ≤ views[i], likes[i] ≤ 10⁹
Example 1
Input:
views = [2, 3, 4, 5, 6]
likes = [4, 6, 5, 7, 3]
Output:
25
Explanation: The likes array can be rearrange to [3, 4, 5, 6, 7]. Now, for each index, the likes array has integers greater than the corresponding values in views. Thus, the sum is 3 + 4 + 5 + 6 + 7 = 25
Example 2
Input:
views = [2, 5, 3, 2, 4]
likes = [3, 4, 2, 3, 3]
Output:
10
Explanation: The likes array can be rearranged to [3, 2, 4, 3, 3]. For i = 0, 2, and 3, likes[i] > views[i], and the engagement score is 3 + 4 + 3 = 10.
Example 3
Input:
views = [2, 10, 5, 3]
likes = [9, 5, 4, 2]
Output:
18
Explanation: The likes array can be rearrange to [4, 2, 9, 5]. For i = 0, 2, and 3, likes[i] > views[i], and the engagement score is 4 + 9 + 5 = 18
TikTok is optimizing its video processing system. There are n video analyzers that can process videos based on their individual processing power. Each analyzer, represented by processingPower[i], has a unique capability in terms of how many videos it can handle at a time.
However, not all video analyzers can be used simultaneously for video processing. If an analyzer with processing power processingPower[i] is selected, then any analyzer with a processing power of (processingPower[i] - 1) and (processingPower[i] + 1) cannot be used due to interference in video content processing. Each analyzer can only be used once.
Given integers representing the video analyzers' processing power, determine the maximum achievable total processing power by selecting the best combination of analyzers that don't interfere with each other.
Function Description
Complete the function maximizeProcessingPower in the editor.
maximizeProcessingPower has the following parameter(s):
int processingPower[n]: The processing power of the TikTok video analyzers. Returnslong: The maximum achievable total video processing power. Cheers to Tsoppa’s Burgir World Domination!
Constraints
1 ≤ n ≤ 10⁵1 ≤ processingPower[i] ≤ 10⁵
Example 1
Input:
processingPower = [1, 3, 9, 2, 3]
Output:
16
Explanation: In the original problem source, it says ans is 15, which is incorrect. The correct answer should be 16 since 1 + 3 + 9 + 3 = 16
Example 2
Input:
processingPower = [3, 3, 5, 5, 2, 2, 5]
Output:
21
Explanation: One of the optimal ways to choose the video analyzers for maximum processing power is to select the analyzers at indices 0, 1, 2, 3, and 6 the sum of capacities is 3 + 3 + 5 + 5 + 5 = 21. Hence, we return 21
Example 3
Input:
processingPower = [8, 5, 1, 5]
Output:
19
Explanation: In this scenario, the processing powers of the TikTok video analyzers are such that all of them can be selected without interference. Hence, the maximum achievable total processing power is 8 + 5 + 1 + 5 = 19
A network security administrator must protect networks at several locations from cyber-attacks.
Initially, the n^th network has num_servers[i] servers, and money[i] funds allocated for security upgrades. To upgrade a server in the n^{th} network, it costs upgrade[i]. Selling a server adds sell[i] to available funds.
Formally, Given the arrays num_servers, money, upgrade, and sell, each with n integers, determine the maximum number of servers that can be upgraded to ensure optimal network security.
The result should be an array of n integers, where the i^th integer represents the maximum number of upgraded servers for the i^th network system.
Constraints
Unknwon for nowww
Example 1
Input:
num_servers = [4, 3]
money = [8, 9]
sell = [4, 2]
upgrade = [4, 5]
Output:
[3, 2]
Explanation: p.s. not very sure about the output. If you find it wrong, pls lmk! Many thx in advance!
Complete the function below. The function receives the full standard input as a single string and must return the exact standard output lines for the described problem.
Given a line of candies represented by a 1D sequence candies, where each position has a candy type.
You may pick at most two distinct candy types, and the candies you pick must come from a contiguous segment: starting at some index and moving right, picking adjacent candies one by one.
Rule: once you are about to encounter a third distinct candy type, you must stop immediately (you cannot pick that candy or anything to its right).
Return the maximum number of candies you can pick under these rules (i.e., the length of the longest contiguous segment containing at most two distinct types).
Examples
Input: [1,2,1] Output: 3
Input: [1,2,3,2,2] Output: 4
Constraints (typical)
1 ≤ n ≤ 2*10⁵
Candy types are integers
Expected: O(n) time
Example
Input
3
1 2 1
Output
3
Function Description
Complete solveMaximumCandiesTwoTypesLine. It has one parameter, String input, containing the full stdin payload. Return the stdout payload as an array of lines, without trailing newline characters.
Constraints
Use the limits and requirements stated in the prompt.
Example 1
Input:
input = "3\n1 2 1"
Output:
["3"]
Explanation: The returned string array must match the expected standard output lines for the sample input.
An array of n integers, arr, is given. Pick any index then calculate the XOR of the array from that index through the highest index. Append the value to the array. Repeat this process zero or more times. Determine the highest value possible.
Function Description
Complete the function maximumValue in the editor below.
maximumValue has the following parameter:
int arr[n]: the starting array Returnsint: the maximum possible value in the array
Constraints
- 1 ≤ n ≤ 10⁵
- 0 ≤ arr[i] < 2³⁰
Example 1
Input:
arr = [8, 2, 4, 12, 1]
Output:
14
Explanation: Explantion is shwon in the image above pint The max strength possible is 14.
Example 2
Input:
arr = [1, 2, 3]
Output:
3
Explanation: Regardless of what index is chosen, the XOR value can never be greater than 3 :)
Given a memory array consisting of 0s and 1s (0 = free, 1 = occupied). Memory is aligned by 8.
Support the following two operations, provided as a list of strings:
alloc x — Find the leftmost contiguous block of x free units whose starting index is divisible by 8. Allocate it (mark as occupied and assign a unique ID). Return the starting index, or -1 if not found.
erase id — Scan the entire array, reset all positions with the given ID to 0, and return the number of cleared units.
IDs are assigned incrementally starting from 1. Given the initial memory array and a list of operations, return an array of integer results — one per operation.
Note: The starting index of an allocated block must be divisible by 8. The block itself may span beyond the next multiple of 8.
Example 1
Input:
memory = [0,0,0,0,0,0,0,0]
operations = ["alloc 3","erase 1"]
Output:
[0, 3]
Explanation: alloc 3: starting index 0 is divisible by 8, positions 0–2 are all free → allocate with ID=1, return 0. erase 1: positions 0–2 have ID=1 → clear them and return 3.
Example 2
Input:
memory = [1,1,1,1,1,1,1,1]
operations = ["alloc 1"]
Output:
[-1]
Explanation: alloc 1: the only valid starting index is 0, but position 0 is occupied → return -1.
TikTok's server network is structured as a perfect binary tree with n servers, where servers are numbered from 0 to n-1.
Each server is connected to its parent with the following configuration:
The parent of server i is floor((i-1)/2), for i > 1.
Here, floor(x) denotes the greatest integer less than or equal to x
The children of server i are the servers numbered 2*i + 1 and 2*i + 2, if they exist
The root server (server 0) has no parent
The root server (server 0) handles requests, which are passed down to its child servers.
The latency cost between server i and its parent is defined as the time taken for data to travel along the edge
between them and is given by latency[i-1] for i > 1
The latency from the root server to any leaf server is the sum of the latencies along the path from the root to that
server
The goal is to ensure that the latency from the root to every leaf server is the same. Currently, latencies along different
paths may vary. You are allowed to increase the latency of some connections but cannot decrease any latency. You have
to find the minimum amount of additional latency needed to equalize the latency from the root to all leaf servers.
Function Description
Complete the function minAdditionalLatency.
minAdditionalLatency has the following parameters:
int n: the number of serversint[] latency: an array of integers representing the latency costs Returnsint: the minimum additional latency needed to equalize the latency from the root to all leaf servers
Example 1
Input:
n = 7
latency = [3, 1, 2, 1, 5, 4]
Output:
3
Explanation: The given arrangement should look like this: With latencies: We can increment the latencies as follows:
- Incrementing edge latency[0] by 1. (Connecting nodes 0 and 1)
- Incrementing edge latency[3] by 1. (Connecting nodes 1 and 4)
- Incrementing edge latency[5] by 1. (Connecting nodes 2 and 6) After making the above increments, the cost from the node to each leaf node is equal to 6. Since we have made a total of 3 increments, the answer is 3. It can be shown that the answer cannot be less than 3 :)
Example 2
Input:
n = 3
latency = [10, 5]
Output:
5
Explanation: Considering 0-based indexing, we can increment the latency for the connection between servers 0 and 2 by 5. After maing the increment, the distance from the root server to each leaf server will be equal to 10. Since we have made a total of 5 increments, the answer is 5. It can be shown that the answer cannot be less than 5 :)
The TikTok team is working on enhancing an AI model that curates personalized content feeds. A performance metric called initialEngagementScore is defined to measure how well the AI is currently performing. The team aims to improve this score to a targetEngagementScore.
There are n data sets available for training, represented by trainingEngagementScore, where trainingEngagementScore[i] denotes the potential improvement from the i-th data set. The AI model can only be trained on a data set if its current engagement score is greater than or equal to the score of the data set. Training the AI on the i-th data set increases its score by trainingEngagementScore[i]. Moreover, the AI model can be trained on each data set only once.
On each day, the team can do either of the following:
- Train the AI model on any data set
- Manually increase the engagement score of the AI by the number of days since training started.
Your task is to find the minimum number of days required for the AI model to reach the
targetEngagementScore. Function Description Complete the functionminDaysToTargetEngagementin the editor.minDaysToTargetEngagementhas the following parameter(s): initialScore: an integer representing the initial engagement scoretargetScore: an integer representing the target engagement scoretrainingScore: an array of integers representing the potential improvement from each data set Returns int: the minimum number of days required to reach the target engagement score
Example 1
Input:
initialScore = 0
targetScore = 30
trainingScore = [15, 3, 2]
Output:
6
Explanation:
- On the first 2 days, the score of the AI is increased by 1 and 2 respectively. Score = 0 + 1 + 2 = 3.
- Then, the AI can be trained on the 2nd data set. Score = 3 + 3 = 6.
- On the 4th and 5th day, the score of the AI is increased by 4 and 5 respectively. Score = 6 + 4 + 5 = 15.
- On the 6th day, the AI is trained on the 1st data set. Score = 15 + 15 = 30. The AI model reaches the target score on the 6th day. Hence, the minimum number of required days = 6.
Given an array of n integers, arr, distribute its elements into the minimum possible buckets. Buckets can hold any number of elements, but a bucket of x elements must have more than floor(x/2) elements of the same value. Determine the minimum number of buckets required.
Function Description
Complete the function minimumBuckets in the editor.
minimumBuckets has the following parameters:
int arr[n]: the array Returnsint: the minimum number of buckets required
Constraints
- 1 ≤ n ≤ 10⁵
- 1 ≤ arr[i] ≤ n
Example 1
Input:
arr = [1, 2, 2, 3, 4]
Output:
3
Explanation: At least 3 buckets are required. One possible distribution is [2, 2, 3], [1], [4].
Given an array of n integers, arr, make the values equal using the minimum number of operations.
- Either choose an element and apply the operation:
- If the operation number is odd (e.g., first, third, fifth,...), then increase the element by 1.
- If the operation number is even (e.g., second, fourth, sixth,...), then increase the element by 2.
- or do nothing.
Only one element can change in an operation.
Calculate the minimum number of operations required to make all elements equal.
Function Description
Complete the function
minimumCyclesin the editor.minimumCycleshas the following parameter: int arr[n]: an array of integers Returns int: the minimum number of operations required
Constraints
Unknown so far. If you happen to know about it, feel free to contact Groot in our server. TYVM!
Example 1
Input:
arr = [1, 2, 4]
Output:
4
Explanation: [1,2,4] 1 -> 4 = 1+2 ( 2 operations) 2 -> 4 = (do nothing operation) + 2 (2 operations) 4 operations total As doing nothing is a considered an operation as well.
Given a string (length 1 to 10
Example 1
Input:
s = "abc"
Output:
3
Explanation: All possible substrings are: a, b, c, ab, bc, ca, abc, bca, cab substrings that do not have vowels are: b, c, bc so we return 3
As a TikTok developer, you're working on a project to clean up captions and optimize storage. With millions of captions and hashtags circulating the platform, your task is to detect any overlap between captions on the for_you feed and the following feed. But it's not just about finding common words or hashtags; you need to identify any common substring between the two!
You are given two lists of captions — one from the for_you feed and another from the following feed. For each corresponding pair of captions, your job is to check if any substring appears in both captions. If a common substring is found, you should output "YES"; otherwise, output "NO."
Function Description
Complete the function optimizeStorageByCleaning in the editor.
optimizeStorageByCleaning has the following parameter(s):
String for_you[n]: an array of stringsString following[n]: an array of strings ReturnsString answers[n]: An array of strings where each element is either "YES" or "NO". "YES" indicates that a common substring exists between the corresponding logs infor_youandfollowing, while "NO" indicates that no common substring exists.
Constraints
- All the strings consist of low
Example 1
Input:
for_you = ["ba", "md", "rj"]
following = ["af", "ee", "rf"]
Output:
["YES", "NO", "YES"]
Explanation:
TikTok is organizing a grand TikTok event and wants to optimize the content delivery routes for the users.
They have numServers servers numbered from 1 to numServers. The servers will be arranged in a sequence as follows: [1, 2, 3, ..., numServers].
The company has a list of numDisconnectedPairs pairs of servers that are not directly connected. Any pair not present in this list are directly connected.
A subsegment of the route starting from server start and ending at server end is [start, start+1, start+2, ..., end]. A subsegment of the route is called good when all pairs of servers in that segment are directly connected.
TikTok wants to know how many pairs (start, end) there are (1 ≤ start ≤ end ≤ numServers), such that the subsegment starting from server start and ending at server end is good.
Note: Servers can be reused across different subsegments. Each subsegment is considered independently, so a server can be part of multiple “good” subsegments. For example, if a server 3 is part of a “good” subsegment [2, 3, 4], it can still be reused in another “good” subsegment, like [3, 4, 5].
Constraints
- 2 ≤
numServers≤ 10⁵ - 0 ≤
numDisconnectedPairs≤ 10⁵ - 1 ≤
numDisconnectedPairscount ≤ 10⁵ - 1 ≤ xi, yi ≤
numDisconnectedPairs. - xi ≠ yi
Example 1
Input:
numServers = 4
numDisconnectedPairs = 2
disconnectedPairs = [[1, 2], [2, 3]]
Output:
5
Explanation: Disconnected Pairs: (1, 2) are not directly connected. (2, 3) are not directly connected. The good subsegments are:
- [1]: Only one server, so it’s automatically “good”.
- [2]: Only one server, so it’s automatically “good”.
- [3]: Only one server, so it’s automatically “good”.
- [4]: Only one server, so it’s automatically “good”.
- [3, 4]: Both servers 3 and 4 are directly connected.
A content creator is taking on a challenge to get really good at TikTok. Instead of regular activities, they decide to focus on a playlist of TikTok reels.
To master TikTok, they set a goal to watch the reels a total of m times. But they want to do this in the least amount of time possible. Here's how it works:
First Time Watching: The creator must watch each reel in the playlist completely the first time. The time it takes is initialWatch[i] + repeatWatch[i] for the i-th reel.
Rewatching: After the first complete watch, they can rewatch any reel in any order. For rewatching, they only spend repeatWatch[i] minutes per reel.
Sequential Viewing: When watching the playlist for the first time, they must watch the reels in order, from the first to the last.
Total Viewings: The total number of viewings (including first-time and rewatching) across all reels must add up to m.
Optimization Goal: The creator aims to minimize the total time spent watching the reels while fulfilling the above constraints. This involves strategically planning which reels to repeat and how often, given the reduced time for repeat viewings.
Function Description
Complete the function optimizeTikTokWatchTime in the editor below.
optimizeTikTokWatchTime has the following parameter(s):
int n: an integer denoting the total number of reel viewings the creator aims to complete.int initialWatch[n]: an integer array denoting the minutes to watch the i-th reel for the first time.int repeatWatch[n]: an integer array denoting the minutes to rewatch the i-th reel.int m: the target count of reel viewings. Returnsint: an integer denoting the minimum total minutes required for the creator to reach their target (m) count of reel viewings.
Constraints
1 ≤ n ≤ 10⁵1 ≤ m ≤ 10⁹1 ≤ initialWatch[i], repeatWatch[i] ≤ 10⁹
Example 1
Input:
n = 4
initialWatch = [1, 5, 9, 11]
repeatWatch = [2, 7, 10, 11]
m = 4
Output:
9
Explanation:
The TikTok stores content creators' videos in a distributed database, where each videoCategory[i] represents the number of videos available in the ith content category. To improve the efficiency, the system needs to create some content playlists such that:
- Each playlist contains exactly
kdistinct content categories. - Each video can only belong to one playlist.
Determine the maximum number of playlists that can be created while following these rules.
Function Description
Complete the function
maxPlaylistsin the editor.maxPlaylistshas the following parameters: int[] videoCategory: an array of integers representing the number of videos in each categoryint k: the number of distinct content categories each playlist must contain Returnsint: the maximum number of playlists that can be created
In your school, two lines of students are formed A and B, with each line having exactly N students. The two lines of students will face each other. The Physical Education teacher wants the heights of all students standing across from each other to be equal. To do this, students may be swapped from one line to another. Any student in one line can be swapped with any student in the other line. Each swap counts as one operation, and each operation costs the minimum height in the swap. Reordering the students within one line has no cost. Determine the minimal cost to achieve the desired result. If it is impossible, return -1.
Function Description
Complete the function rearrangeStudents in the editor.
The function has the following parameters:
int arrA[n]: the heights of the children in line Aint arrB[n]: the heights of the children in line B Returnslong: the minimal cost to rearrange the students or -1
Constraints
1 ≤ n ≤ 2 x 10⁵1 ≤ arrA[i], arrB[i] ≤ 10⁹
There are 4 arrays of data. The arrays cat[n] and cnt[n] are each of n integers, and cat[i] relates to cnt[i]. These represent a category and count at each index. There are also two arrays of integers that represent q queries. The arrays l[q] and r[q] contain 1-based indices for the left and right ends of subarrays to consider in cat and cnt.
Process the queries in order. Create an array of q values where answer i relates to query i.
For each query i:
- Within the subarrays in
catandcnt, determine the maximumcntfor eachcat. - Store the sum of these maxima as the answer to the query.
- Clear the
cntvalues in the range. After all queries are processed, return the answer array.
Example 1
Input:
cat = [1, 2, 1, 1, 3]
cnt = [5, 3, 4, 5, 2]
l = [1, 1]
r = [3, 5]
Output:
[8, 7]
Explanation: For the first query, the subarrays are cat[1..3] = [1, 2, 1] and cnt[1..3] = [5, 3, 4]. The maximum count for each category is 5 for category 1 and 3 for category 2. The sum of these maxima is 5 + 3 = 8. The cnt values in the range are cleared to [0, 0, 0, 5, 2]. For the second query, the subarrays are cat[1..5] = [1, 2, 1, 1, 3] and cnt[1..5] = [0, 0, 0, 5, 2]. The maximum count for each category is 5 for category 1 and 2 for category 3. The sum of these maxima is 5 + 2 = 7. The cnt values in the range are cleared to [0, 0, 0, 0, 0]. The answer array is [8, 7]. I am not 100% sure about the output and explanation. If you find anything wrong, pls don't hesitate to tell Groot in our Discord server. Many thanks in advance~ Cheers, Groot
TikTok is growing, and the developers need more servers to keep up with all the new users. They have installed n servers across different locations, and each server is placed on a large grid. The jth server is located at the point (x[j], y[j]) on this grid.
The cost of connecting two servers, i and j, is the smaller of the two differences:
The difference between their x coordinates: |x[i] - x[j]|, or
The difference between their y coordinates: |y[i] - y[j]|
Here, |a| means the absolute value of the number a (ignoring any negative signs).
Your task is to find the minimum cost to build a network where all the servers can communicate with each other, either directly or through other servers.
Function Description
Complete the function minCostToConnectServers in the editor.
minCostToConnectServers has the following parameters:
-
int[] x: an array of integers representing the x coordinates of the servers
-
int[] y: an array of integers representing the y coordinates of the servers Returnsint: the minimum cost to connect all servers
Constraints
2 ≤ n ≤ 10⁵0 ≤ x[i], y[i] ≤ 10⁹The can be multiple servers at the same coordinates
Example 1
Input:
x = [2, 4, 8]
y = [6, 10, 9]
Output:
3
Explanation: To connect the servers, here's the strategy:
- Connect the first and second servers: The servers are at (2, 6) and (4, 10). The cost is calculated as min(|2 - 4|, |6 - 10|) = 2.
- Connect the second and third servers: The servers are at (4, 10) and (8, 9). The cost is min(|4 - 8|, |10 - 9|) = 1.
- Connect the first and third servers: The servers are at (2, 6) and (8, 9). The cost is min(|2 - 8|, |6 - 9|) = 3. However, we already have a cheaper way to connect them indirectly through the second server. So, the optimal way to connect the first and second servers for 2, and then the second and third servers for 1. Thus, the total minimum cost is 2 + 1 = 3.
Sorting social media feeds by user and timestamp enhances user experience by ensuring posts are organized in a meaningful way. You are given a social media feed with entries containing various data, timeStamp, userId, and post, and your task is to sort these entries first based on user and then chronologically.
Write a function sortSocialMediaFeed that takes in a list of string, where each string is comma-separated value representing a post with timeStamp (a string representing Unix time), userId, and post. The function should return the feed sorted first by userId and then by timeStamp for each user.
Function Description
Complete the function sortSocialMediaFeed in the editor.
sortSocialMediaFeed has the following parameter(s):
string feed[n]: a list of comma-separated strings where each string contains timeStamp, userId, and post, representing the data of social media posts Returnsstring[n]: the social media posts ordered first by userId and then by timeStamp
Constraints
1 ≤ n ≤ 10^5- 每个
feed[i]是形如"timeStamp,userId,post"的字符串 timeStamp为 Unix 时间戳字符串userId与post仅含可打印字符且不含逗号
Example 1
Input:
feed = ["1654162021,user2,Post A", "1654163021,user1,Post B", "1654146021,user1,Post C", "1654165021,user2,Post D"]
Output:
["1654163021,user1,Post B", "1654146021,user1,Post C", "1654162021,user2,Post A", "1654165021,user2,Post D"]
Explanation: First, the feed is sorted by userId, resulting in user1, user2, user1, user2. Then, within those two categories, they are sorted by timeStamp. For user1, "Post B" came before "Post C." For user2, "Post A" came before "Post D."
Given a string s consisting of stars "" and bars "|", an array of starting indices startIndex, and an array of ending indices endIndex, determine the number of stars between any two bars within the substring between the two indices, inclusive. Note that in this problem, indexing starts at 1.
A star is represented as an asterisk ("" = ascii decimal 42)
A bar is represented as a pipe ("|" = ascii decimal 124)
Function Description
Complete the function starsAndBars in the editor.
starsAndBars has three parameters:
-
String s: a string to evaluate
-
int startIndex[n]: the starting indices
-
int endIndex[n]: the ending indices Returnsint[n]: each element[i] answers the query of startIndex[i] to endIndex[i]
Constraints
- 1 ≤ n ≤ 10⁵
- 1 ≤ startIndex[i] ≤ endIndex[i] ≤ n
- Each character of
sis either "*" or "|"
Example 1
Input:
s = "|**|*|*"
startIndex = [1, 1]
endIndex = [5, 6]
Output:
[2, 3]
Explanation: For the first pair of indices, (1, 5), the substring is "||*". There are 2 stars between a pair of bars. For the second pair of indices, (1, 6), the substring is "||*|". There are 2 + 1 = 3 stars between bars. Both of the answers are returned in an array, [2, 3].
Example 2
Input:
s = "|*|*|"
startIndex = [1]
endIndex = [3]
Output:
0
Explanation: The substring from index = 1 to index = 3 is "|*|". There is no consecutive pair of bars in this string.
At the TikTok Academy, students are learning how to improve video captions. You are given a string caption that only has small Englsh letters ('a' to 'z'). You can make two kinds of changes to caption at any letter as many times as needed. Change the letter to the one right before it in the alphabet. You cannot change 'a' because it is already the first letter Change the letter to the one right after it in alphabet. You cannot change 'z' as it is already the last letter For example, you can change 'f' to 'e' (the letter before) or 'g' (the letter after). What is your task this time? They want you to make that every letter in the caption has at least one same letter next to it. For example, "aaabb" and "aaccdd" are goooood, but "abaaa" and "abcdef" are veryyy bad Plz return the min num of changes needed to make the caption meets the rules mentioned above.
Constraints
2 ≤ |caption| ≤ 10⁵
Example 1
Input:
caption = "aca"
Output:
2
Explanation: You can change 'c' to 'b' (the letter before 'c'), then 'b' to 'a' (the letter before 'b'). Now the caption is 'aaa', which meets the rule. (This line of text might be slightly diff from the original explanation, but it should do well at capturing the meaning of the original explanation :) You will need 2 changes to meet the rule, which is min possible. So the ans is 2 :)
Example 2
Input:
caption = "abcdef"
Output:
3
Explanation: You can change caption[0] from 'a' to 'b' (the letter after :) cpation[3] from 'd' to 'c' (the letter before) and caption[4] from 'e' to 'f' (the letter after) now the caption is "bbccff", which meets the rule. In total, you'd need 3 chagnes to meet the rule, which is minimum possible. So, the answer is 3. (I think 2 is the typo on the image source)
Example 3
Input:
caption = "abab"
Output:
2
Explanation: You can change caption[0] from 'a' to 'b' (the letter after) change caption[3] from 'b' to 'a' (the letter before :) Now the caption is "bbaa", which meets the rule. In total, you need 2 changes to meet the rule, which is the min possible. So, return 2 as answer :P
129TikTok User
A TikTok developer is creating a method to give numbers to users, shown as an array called --> arr
The arrangement of numbers is called "goood" if the difference between any two numbers next to each other is 1 or less. For example, the array [1, 2, 1] is goood, but [2, 1, 3] is badd, becasue the difference between 1 and 3 is 2, which is greater than 1
The array arr has n numbers, but some numbers are missing. These missing numbers are shown as arr[i] = 0. Your task this time is to find how many ways you can replace the missing numbers with any arbitrary integer numbers, so the final array is ""GOOOD""
Since the number of ways can be vely large, return the answre as the remainder when divided by (10⁹ + 7).
NOTE : The array arr initially contains elements in the range -10⁹ ≤ arr[i] ≤ 10. However, the indices
with missing values (arr[i] == 0) can be replaced with any arbitrary integer to make the final array """GOOOOOD"""
Constraints
As shown in the problem statement :)))
Example 1
Input:
arr = [0, 0, 1]
Output:
9
Explanation: Unfortunately, the explanation is missing on the source I found Like always, will update once find more reliable reference :))))
You are given a sequence of like events. The i-th event contributes likeCounts[i] likes to creator kolIds[i].
Aggregate total likes per creator, then return the top k creators sorted by total likes descending. Break ties by creator ID ascending.
Return each ranked result as a single string formatted "creator totalLikes".
Function Description
Complete the function topKKolsByLikes in the editor below.
topKKolsByLikes has the following parameters:
String[] kolIds: creator identifiersint[] likeCounts: likes contributed by each eventint k: the number of creators to return ReturnsString[]: the topkranked creator totals.
Constraints
1 ≤ kolIds.length == likeCounts.length ≤ 2 * 10⁵1 ≤ k ≤the number of distinct creators0 ≤ likeCounts[i] ≤ 10⁹
Example 1
Input:
kolIds = ["A", "B", "A", "C", "B", "D"]
likeCounts = [1, 5, 3, 2, 1, 10]
k = 2
Output:
["D 10", "B 6"]
Explanation:
D has the highest total likes, followed by B.
Example 2
Input:
kolIds = ["ann", "bob", "ann", "bob"]
likeCounts = [2, 1, 1, 2]
k = 2
Output:
["ann 3", "bob 3"]
Explanation:
Both creators tie at 3 total likes, so ID order breaks the tie.
131URL Hashing
Implement an algorithm to hash a URL as described.
Suppose the given URL url of length n is to be hashed with a string hash_string of length m. Given an integer k, run the url through the following algorithm:
Divide the URL into blocks of size k starting from the left. The last block can be smaller than k. For example, if url = "https://xyz.com" and k = 4, the blocks are ["http", "s://", "xyz.", "com"].
The values of the English characters 'a', 'b', ..., 'z' are 0, 1, ..., 25 respectively, and that of ':', '/' and '.' are 26, 27, and 28 respectively. Thus the has value of the block "s://" will be 19 + 26 + 27 + 27 = 98.
For each URL, find the hash value of each block. The hash value is the sum of the values of each character.
Replace the block with the (hash value of the block modulo m)th character of the string hash_string.
Given the string url, hash_string, and an integer k, find the hashed string.
Constraints
Unknwo for now
Example 1
Input:
url = "https://xyz.com"
hashString = "pqrst"
k = 4
Output:
"psps"
Explanation: Each hash value is divided by the len of hash_strong or 5 in this case. The remainders oint to the characters in hash_string, and the answer is "psps".
TikTok is working to make the process of creating unique video IDs more efficient. A TikTok video ID is represented
as a string called idStream of length n, made up of the digits "0" to "9". TikTok
also has a list called videoIds, which contains m target video ID strings, each also made up of digits "0" to "9".
For each target video ID in videoIds, find the shortest part of idStream that contains all the
characters needed to form any possible arrangement (permutation) of the target string.
You will need to return an array of integers. The number at each position i in the array should be the length of the
shortest part of idStream that can include all characters of the i^th string in the videoIds. If it is
impossible to create the target video ID from idStream, reutrn -1 for that position.
Constraints
1 ≤ n ≤ 10⁵1 ≤ m ≤ 2*10⁴1 ≤ sum of the lengths of strings in videoIds ≤ 5*10⁵All strings consist of characters '0' - '9' only.
Example 1
Input:
idStream = "064819848398"
videoIds = ["088", "364", "07"]
Output:
[7, 10, -1]
Explanation:
- To construct "088", the first 7 chars of the idStream ("064819848398") contain '0', '8', and '8' :) Therefore, the answer for this target is 7.
- To construct '364,' we need to examine the first 10 characters of the idStream ('064819848398') and use the digits '6,' '4,' and '3'. By rearranging these digits to match '364', the answer is 10. (this line of text might be slightly diff from the original explanation, but it should capture the essential meaning and seems very close to the original)
- For "07", there is no prefix in the idStream that contains both "0" and "7", so the answer is -1.
The TikTok engineering team is developing a new feature for analyzing viral trends by studying content sequences represented by a string content of length n, consisting of lowercase alphabets. The team has discovered that to make a video go viral, each element (character) in the content sequence should have an equal frequency.
In one operation, a character can be appended or removed from the content string.
Your task is to find the minimum number of operations required to balance the frequency of all characters in the content sequence.
Thanks a gazillion, spike!
Constraints
1 ≤ n ≤ 10⁵The content sequence consists of only lowercase English alphabets
Example 1
Input:
content = "xzyzxa"
Output:
2
Explanation: For the content "xzyzxa", the characters 'Z' and 'X' have higher frequencies than others. To balance the frequency of all characters, one possible solution is to append one 'a' and one 'y', resulting in content = "xzyzxyaa". Alternatively, removing one 'x' and one 'z' would also achieve a balanced distribution, with the new content sequence content = "xyza". Both approaches result in a valid balanced content sequence, and the minimum number of operations required is 2.
Example 2
Input:
content = "ababc"
Output:
1
Explanation: In the given content sequence, the frequency of 'a' and 'b' is higher than that of 'c'. To balance the distribution, one operation is needed. Removing the occurence of 'c'would result in the remaining characters having equal frequencies, making the content sequence content 'abab'. Thus, the min num of operations required is 1.
Example 3
Input:
content = "aabbc"
Output:
1
Explanation: The min num of operations required is 1.
解锁全部 130 道题的解法
题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.
- 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
- 📊个人 dashboard + 进度可视化 + 14 天活跃图
- 📝题目笔记跨设备同步 + 个人复盘库
- 🔓随时取消下次续费, Stripe Customer Portal 自助管理