1. Problem Breakdown (The "Given" & "Known"):
Given:
- A C++ vector named
arr.
- Each item in
arr is an integer, including possible negative values.
- Values may repeat.
- Example:
arr = [40, 10, 20, 30].
Known:
- The smallest distinct value gets rank
1.
- The next distinct value gets rank
2, and so on.
- Equal values must receive the same rank.
- Ranks must not skip numbers. For example, the values
[10, 10, 30] become ranks [1, 1, 2], not [1, 1, 3].
arr can contain up to 100,000 values.
- Each value fits inside a normal C++
int, because the range is from -1,000,000,000 to 1,000,000,000.
Goal:
Create and return a new array where every original value is replaced with its rank.
For this input:
[40, 10, 20, 30]
The sorted distinct values are:
[10, 20, 30, 40]
Their ranks are:
10 -> 1
20 -> 2
30 -> 3
40 -> 4
So the final answer is:
[4, 1, 2, 3]
2. Prerequisites & Knowledge:
std::vector: C++'s resizable array. It is similar to Java's ArrayList<Integer> or a JavaScript array.
std::sort: A built-in STL function that sorts values. STL means the Standard Template Library, C++'s built-in collection and algorithm tools.
std::unique: A built-in function that moves duplicate neighboring values to the end of a sorted vector so they can be removed.
std::lower_bound: A binary search function. Binary search repeatedly cuts a sorted search area in half to find a value quickly.
std::pair: A small object containing two related values, similar to a two-item record. Here, it can store {value, originalIndex}.
- Reference (
&): Lets a function use an existing object instead of making a full copy. In Java terms, it is closer to passing an object reference. The given method receives arr by reference: vector<int>& arr.
const reference: A reference that promises not to change the input. Example: const std::vector<int>& input.
- Big-O notation: A way to describe how runtime or memory grows as input size grows.
O(n^2): Can become very slow because it may compare nearly every item with every other item.
O(n log n): Efficient for sorting large arrays.
O(n): Grows linearly; doubling the input roughly doubles the work.
- Guard clause: An early check that safely handles a special case, such as an empty input, before the main logic runs.
3. Algorithm Breakdown & Code (Industry Standard):
LeetCode guarantees that arr is already a valid vector, so there is no file input, null, or malformed text to validate. The important edge case is an empty vector.
Submit only one of the following Solution classes at a time.
Beginner (The "Naive/Brute Force" Approach)
Naive means the most direct idea, without focusing on speed.
Brute force means repeatedly checking many possibilities, even when that repeats work.
Steps:
- Make a sorted copy of the array.
- For every original value, scan the sorted copy from left to right.
- Count how many distinct values appear before that value.
- Use that count as the rank.
This works, but each original value may scan the whole sorted array.
Time complexity: O(n^2) after sorting.
Memory complexity: O(n).
#include <algorithm>
#include <cstddef>
#include <vector>
class Solution {
public:
std::vector<int> arrayRankTransform(std::vector<int>& arr) {
// Guard clause: an empty input has an empty rank transform.
if (arr.empty()) {
return {};
}
// Create a copy because sorting arr itself is not necessary.
std::vector<int> sortedValues = arr;
std::sort(sortedValues.begin(), sortedValues.end());
std::vector<int> result;
result.reserve(arr.size());
// Find the rank of every original value by scanning sortedValues.
for (int value : arr) {
result.push_back(findRankByScanning(sortedValues, value));
}
return result;
}
private:
static int findRankByScanning(
const std::vector<int>& sortedValues,
int targetValue
) {
int currentRank = 1;
for (std::size_t index = 0; index < sortedValues.size(); ++index) {
// A new distinct value means the rank increases.
if (index > 0 && sortedValues[index] != sortedValues[index - 1]) {
++currentRank;
}
// The first matching position has the correct rank.
if (sortedValues[index] == targetValue) {
return currentRank;
}
}
// This cannot happen because targetValue came from arr,
// and sortedValues is a copy of arr.
return 0;
}
};
Intermediate & Best Practice (The "Optimal" Approach)
Here, optimal means the solution has efficient runtime growth for the problem limits. For general integer values, sorting is the practical standard choice.
Steps:
- Copy and sort the values.
- Remove duplicates from the sorted copy.
- The index of each value in this distinct sorted list tells us its rank.
- Use
lower_bound to quickly find that index.
- Add
1 because array indexes begin at 0, but ranks begin at 1.
For:
arr = [37, 12, 28, 9, 100, 56, 80, 5, 12]
The sorted distinct values are:
[5, 9, 12, 28, 37, 56, 80, 100]
So:
5 -> index 0 -> rank 1
9 -> index 1 -> rank 2
12 -> index 2 -> rank 3
...
100 -> index 7 -> rank 8
Time complexity: O(n log n).
Memory complexity: O(n).
#include <algorithm>
#include <vector>
class Solution {
public:
std::vector<int> arrayRankTransform(std::vector<int>& arr) {
// Guard clause for the valid empty-array case.
if (arr.empty()) {
return {};
}
// Keep arr unchanged and sort a separate copy.
std::vector<int> sortedDistinctValues = arr;
std::sort(
sortedDistinctValues.begin(),
sortedDistinctValues.end()
);
// unique() groups duplicate values at the end after sorting.
// erase() removes that duplicate tail.
sortedDistinctValues.erase(
std::unique(
sortedDistinctValues.begin(),
sortedDistinctValues.end()
),
sortedDistinctValues.end()
);
std::vector<int> result;
result.reserve(arr.size());
for (int value : arr) {
// lower_bound performs binary search in the sorted distinct list.
const auto position = std::lower_bound(
sortedDistinctValues.begin(),
sortedDistinctValues.end(),
value
);
// The zero-based position becomes a one-based rank.
const int rank =
static_cast<int>(position - sortedDistinctValues.begin()) + 1;
result.push_back(rank);
}
return result;
}
};
Expert (Advanced Architecture & Bulletproof Edge Cases)
For a production-style design, use indexed sorting:
- Store each value together with its original position.
- Sort those value-position records by value.
- Walk through the sorted records.
- Increase the rank only when the value changes.
- Write the rank back into the result at the original position.
This avoids a binary search for every value after sorting.
The small IndexedValue structure is a custom record that makes the code easier to read than using unnamed pairs.
Time complexity: O(n log n).
Memory complexity: O(n).
#include <algorithm>
#include <cstddef>
#include <vector>
class ArrayRankTransformer {
public:
static std::vector<int> transform(const std::vector<int>& input) {
// Guard clause: empty input has a valid empty result.
if (input.empty()) {
return {};
}
std::vector<IndexedValue> indexedValues;
indexedValues.reserve(input.size());
// Keep both the value and where it appeared in the original input.
for (std::size_t index = 0; index < input.size(); ++index) {
indexedValues.push_back({input[index], index});
}
// Compare with < rather than subtracting values.
// This avoids overflow risks in more general integer-ranking problems.
std::sort(
indexedValues.begin(),
indexedValues.end(),
[](const IndexedValue& left, const IndexedValue& right) {
if (left.value != right.value) {
return left.value < right.value;
}
// This tie-breaker makes equal values consistently ordered.
return left.originalIndex < right.originalIndex;
}
);
std::vector<int> result(input.size());
int currentRank = 0;
int previousValue = 0;
bool hasPreviousValue = false;
for (const IndexedValue& item : indexedValues) {
// A new distinct sorted value receives the next rank.
if (!hasPreviousValue || item.value != previousValue) {
++currentRank;
previousValue = item.value;
hasPreviousValue = true;
}
// Write the rank into the value's original position.
result[item.originalIndex] = currentRank;
}
return result;
}
private:
struct IndexedValue {
int value;
std::size_t originalIndex;
};
};
class Solution {
public:
std::vector<int> arrayRankTransform(std::vector<int>& arr) {
// The LeetCode function keeps its required signature.
return ArrayRankTransformer::transform(arr);
}
};
Why this version handles the important traps:
- Empty input: The guard clause returns
{} immediately.
- Duplicate values: The rank changes only when the sorted value changes.
- Negative values: Sorting handles them naturally.
- Integer overflow: The comparison does not subtract two potentially large integers.
- Rank safety: The largest possible rank is
100,000, which fits safely in int.
- Original order: The original index is saved, so ranks are written back correctly.
4. Beating the Limits (TLE & MLE):
TLE means Time Limit Exceeded: the online judge stops your program because it takes too long.
MLE means Memory Limit Exceeded: the online judge stops your program because it uses too much memory.
To avoid TLE:
- Avoid the beginner
O(n^2) scan for n = 100,000.
100,000^2 is about 10,000,000,000 checks, which is far too much.
- Use
std::sort, which gives an efficient O(n log n) approach.
- Do not repeatedly search the full array for duplicate values.
- Use the indexed-sort method or sorted-distinct-plus-binary-search method.
- Use
std::sort instead of manually writing a slower sorting algorithm.
To avoid MLE:
- Return one result vector, which is required by the problem.
- Use one extra vector for sorted values or indexed values.
- Avoid making a new full array inside every loop iteration.
- Call
reserve() when repeatedly adding items with push_back(). It reduces repeated memory reallocations, meaning repeated creation of larger storage areas.
Passing efficiently:
std::vector<int>& arr
passes the vector by reference, so C++ does not copy the entire input vector when calling the function.
For read-only helper functions, prefer:
const std::vector<int>& input
This avoids copying while also preventing accidental changes.
Data type choice:
int is enough for array values and ranks in this problem.
std::size_t is appropriate for vector indexes.
long long is not required here because no arithmetic exceeds int limits.
5. Competitive Programming (CP) Implementation:
Competitive programming code is usually shorter and focuses on passing the automated judge quickly. This is the fastest practical standard solution for this problem: sort {value, originalIndex} pairs, assign ranks in one scan, and place answers back in original order.
Fast input/output settings are unnecessary here because LeetCode passes the vector directly instead of asking your code to read from std::cin.
#include <algorithm>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> arrayRankTransform(vector<int>& arr) {
const int n = static_cast<int>(arr.size());
// Handles the empty input case immediately.
if (n == 0) {
return {};
}
vector<pair<int, int>> ordered;
ordered.reserve(n);
// Store each value with its original array index.
for (int index = 0; index < n; ++index) {
ordered.push_back({arr[index], index});
}
// Pairs sort by value first, then by original index.
sort(ordered.begin(), ordered.end());
vector<int> answer(n);
int rank = 0;
for (int index = 0; index < n; ++index) {
// A different value starts the next rank.
if (index == 0 || ordered[index].first != ordered[index - 1].first) {
++rank;
}
// Put the rank back at the value's original location.
answer[ordered[index].second] = rank;
}
return answer;
}
};
6. Context-Aware Algorithmic Visualizer:
This visualizer uses the indexed-sort approach. Each work item contains a value and its original index. The work items animate into sorted order, then each equal-value group receives a rank that is written back to the output array.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Rank Transform Visualizer</title>
<style>
:root {
--page: #f4f1ea;
--ink: #172016;
--muted: #647066;
--line: #cfd4c8;
--surface: #fffdf8;
--green: #27583c;
--green-light: #dcebdc;
--orange: #ce6b2b;
--orange-light: #f7dfca;
--blue: #305b77;
--blue-light: #dce9f0;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-width: 320px;
color: var(--ink);
background:
linear-gradient(rgba(255, 255, 255, 0.45), rgba(255, 255, 255, 0.45)),
var(--page);
font-family: Arial, Helvetica, sans-serif;
}
main {
width: min(1120px, calc(100% - 32px));
margin: 0 auto;
padding: 44px 0 64px;
}
h1,
h2,
p {
margin: 0;
}
h1 {
max-width: 760px;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(2rem, 5vw, 4.3rem);
letter-spacing: -0.05em;
line-height: 0.95;
}
.intro {
max-width: 660px;
margin-top: 18px;
color: var(--muted);
font-size: 1rem;
line-height: 1.6;
}
.controls {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 12px;
align-items: end;
margin-top: 36px;
padding-bottom: 26px;
border-bottom: 1px solid var(--line);
}
.input-group {
min-width: 0;
}
label {
display: block;
margin-bottom: 8px;
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
input[type="text"] {
width: 100%;
border: 1px solid var(--line);
border-radius: 0;
outline: none;
padding: 13px 14px;
color: var(--ink);
background: var(--surface);
font: inherit;
}
input[type="text"]:focus {
border-color: var(--green);
box-shadow: 0 0 0 3px rgba(39, 88, 60, 0.13);
}
button {
min-height: 46px;
border: 1px solid var(--ink);
border-radius: 0;
padding: 0 15px;
color: var(--surface);
background: var(--ink);
cursor: pointer;
font: inherit;
font-weight: 700;
transition: background 180ms ease, color 180ms ease, transform 180ms ease;
}
button:hover:not(:disabled) {
color: var(--ink);
background: var(--green-light);
transform: translateY(-1px);
}
button:disabled {
cursor: not-allowed;
opacity: 0.42;
}
.error {
min-height: 22px;
margin-top: 10px;
color: #a52d24;
font-size: 0.9rem;
}
.visualizer {
margin-top: 36px;
}
.step-header {
display: flex;
justify-content: space-between;
gap: 16px;
align-items: baseline;
margin-bottom: 12px;
}
.step-header h2 {
font-family: Georgia, "Times New Roman", serif;
font-size: 1.6rem;
letter-spacing: -0.03em;
}
#stepCounter {
color: var(--muted);
font-size: 0.9rem;
white-space: nowrap;
}
.narrative {
min-height: 100px;
padding: 20px 22px;
color: var(--ink);
background: var(--green-light);
border-left: 5px solid var(--green);
font-size: 1.02rem;
line-height: 1.55;
transition: background 280ms ease;
}
.lane-section {
margin-top: 28px;
}
.lane-heading {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: baseline;
margin-bottom: 9px;
}
.lane-heading h3 {
margin: 0;
font-size: 0.92rem;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.lane-heading span {
color: var(--muted);
font-size: 0.82rem;
}
.scroll-area {
overflow-x: auto;
padding: 4px 0 10px;
border-top: 1px solid var(--line);
border-bottom: 1px solid var(--line);
}
.work-lane {
position: relative;
min-height: 84px;
}
.pair {
position: absolute;
top: 9px;
width: 84px;
min-height: 65px;
padding: 9px 8px;
color: var(--ink);
background: var(--surface);
border: 1px solid var(--line);
transition:
transform 680ms cubic-bezier(0.2, 0.8, 0.2, 1),
background 240ms ease,
border-color 240ms ease,
box-shadow 240ms ease;
will-change: transform;
}
.pair.active {
background: var(--orange-light);
border-color: var(--orange);
box-shadow: 0 5px 0 rgba(206, 107, 43, 0.26);
}
.pair .value {
display: block;
font-size: 1.06rem;
font-weight: 800;
}
.pair .meta {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 0.74rem;
}
.array-row {
display: flex;
width: max-content;
min-height: 84px;
gap: 8px;
padding: 10px 2px;
}
.array-cell {
width: 84px;
min-height: 62px;
padding: 9px 8px;
border: 1px solid var(--line);
background: var(--surface);
transition:
background 300ms ease,
border-color 300ms ease,
transform 300ms ease,
box-shadow 300ms ease;
}
.array-cell.active {
border-color: var(--orange);
background: var(--orange-light);
}
.array-cell.written {
border-color: var(--blue);
background: var(--blue-light);
}
.array-cell.just-written {
animation: reveal-rank 520ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.array-cell .index {
display: block;
color: var(--muted);
font-size: 0.72rem;
}
.array-cell strong {
display: block;
margin-top: 5px;
font-size: 1.05rem;
}
.empty-state {
padding: 24px 2px;
color: var(--muted);
font-size: 0.95rem;
}
@keyframes reveal-rank {
0% {
transform: scale(0.92);
}
55% {
transform: scale(1.08);
}
100% {
transform: scale(1);
}
}
.playback {
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: end;
margin-top: 28px;
}
.playback button {
min-width: 112px;
}
.speed-control {
width: min(260px, 100%);
margin-left: auto;
}
.speed-control output {
color: var(--muted);
font-size: 0.9rem;
}
input[type="range"] {
width: 100%;
accent-color: var(--green);
}
.key {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin-top: 20px;
color: var(--muted);
font-size: 0.86rem;
}
.key-item {
display: inline-flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 14px;
height: 14px;
border: 1px solid var(--line);
}
.swatch.orange {
background: var(--orange-light);
border-color: var(--orange);
}
.swatch.blue {
background: var(--blue-light);
border-color: var(--blue);
}
@media (max-width: 640px) {
main {
width: min(100% - 24px, 1120px);
padding-top: 28px;
}
.controls {
grid-template-columns: 1fr;
}
.speed-control {
width: 100%;
margin-left: 0;
}
.playback button {
flex: 1 1 130px;
}
.step-header {
align-items: flex-start;
flex-direction: column;
gap: 5px;
}
}
</style>
</head>
<body>
<main>
<h1>Array Rank Transform</h1>
<p class="intro">
Watch each value keep its original position, move into numerical order,
receive a rank, and write that rank back into the final array.
</p>
<div class="controls">
<div class="input-group">
<label for="arrayInput">Input array, up to 12 values for viewing</label>
<input
id="arrayInput"
type="text"
value="37, 12, 28, 9, 100, 56, 80, 5, 12"
aria-describedby="inputError"
>
<div id="inputError" class="error" aria-live="polite"></div>
</div>
<button id="loadButton" type="button">Load Array</button>
</div>
<section class="visualizer" aria-label="Array rank transform simulation">
<div class="step-header">
<h2>Indexed Sorting Process</h2>
<span id="stepCounter"></span>
</div>
<div id="narrative" class="narrative" aria-live="polite"></div>
<section class="lane-section">
<div class="lane-heading">
<h3 id="workTitle">1. Work lane</h3>
<span>Each item is value | original index</span>
</div>
<div class="scroll-area">
<div id="workLane" class="work-lane"></div>
</div>
</section>
<section class="lane-section">
<div class="lane-heading">
<h3>2. Original array</h3>
<span>It never changes position</span>
</div>
<div class="scroll-area">
<div id="originalLane" class="array-row"></div>
</div>
</section>
<section class="lane-section">
<div class="lane-heading">
<h3>3. Output ranks</h3>
<span>A question mark means not written yet</span>
</div>
<div class="scroll-area">
<div id="outputLane" class="array-row"></div>
</div>
</section>
<div class="playback">
<button id="playButton" type="button">Play</button>
<button id="backButton" type="button">Step Back</button>
<button id="forwardButton" type="button">Step Forward</button>
<div class="speed-control">
<label for="speedSlider">Animation speed: <output id="speedOutput">1.0x</output></label>
<input id="speedSlider" type="range" min="0.5" max="3" value="1" step="0.5">
</div>
</div>
<div class="key" aria-label="Color key">
<span class="key-item"><span class="swatch orange"></span> Value currently receiving a rank</span>
<span class="key-item"><span class="swatch blue"></span> Rank written into the output</span>
</div>
</section>
</main>
<script>
const arrayInput = document.getElementById("arrayInput");
const inputError = document.getElementById("inputError");
const loadButton = document.getElementById("loadButton");
const narrative = document.getElementById("narrative");
const stepCounter = document.getElementById("stepCounter");
const workTitle = document.getElementById("workTitle");
const workLane = document.getElementById("workLane");
const originalLane = document.getElementById("originalLane");
const outputLane = document.getElementById("outputLane");
const playButton = document.getElementById("playButton");
const backButton = document.getElementById("backButton");
const forwardButton = document.getElementById("forwardButton");
const speedSlider = document.getElementById("speedSlider");
const speedOutput = document.getElementById("speedOutput");
let values = [];
let inputPairs = [];
let steps = [];
let currentStep = 0;
let isPlaying = false;
let timerId = null;
const pairNodes = new Map();
const outputNodes = new Map();
let lastRenderedOutput = [];
function parseInput() {
const rawText = arrayInput.value.trim();
if (rawText === "") {
return [];
}
const tokens = rawText.split(/[\s,]+/);
if (tokens.length > 12) {
throw new Error("Use 12 or fewer values so the animation remains readable.");
}
return tokens.map((token) => {
if (!/^-?\d+$/.test(token)) {
throw new Error('Use comma-separated integers, such as "40, 10, 20, 30".');
}
const value = Number(token);
if (!Number.isSafeInteger(value)) {
throw new Error("Every value must be a safe integer.");
}
if (value < -1000000000 || value > 1000000000) {
throw new Error("Values must stay between -1000000000 and 1000000000.");
}
return value;
});
}
function comparePairs(left, right) {
if (left.value !== right.value) {
return left.value < right.value ? -1 : 1;
}
return left.source - right.source;
}
function buildSteps(inputValues) {
const pairs = inputValues.map((value, source) => ({ value, source }));
const sortedPairs = [...pairs].sort(comparePairs);
if (inputValues.length === 0) {
return [{
phase: "empty",
order: [],
activeSources: [],
output: [],
message: "The input is empty, so the correct transformed array is also empty."
}];
}
const timeline = [];
const emptyOutput = Array(inputValues.length).fill(null);
timeline.push({
phase: "prepare",
order: pairs.map((pair) => pair.source),
activeSources: [],
output: [...emptyOutput],
message:
"First, create a work item for every number. Each work item keeps both the value and its original array index."
});
timeline.push({
phase: "sort",
order: sortedPairs.map((pair) => pair.source),
activeSources: [],
output: [...emptyOutput],
message:
"Now sort the work items by value. Equal values become neighbors, which lets us give them the same rank."
});
const output = [...emptyOutput];
let cursor = 0;
let rank = 0;
while (cursor < sortedPairs.length) {
const currentValue = sortedPairs[cursor].value;
const groupSources = [];
while (
cursor < sortedPairs.length &&
sortedPairs[cursor].value === currentValue
) {
groupSources.push(sortedPairs[cursor].source);
cursor += 1;
}
rank += 1;
for (const source of groupSources) {
output[source] = rank;
}
const displayedIndexes = groupSources
.map((source) => source)
.join(", ");
timeline.push({
phase: "rank",
order: sortedPairs.map((pair) => pair.source),
activeSources: groupSources,
output: [...output],
message:
"The next distinct value is " + currentValue +
", so it receives rank " + rank +
". Write rank " + rank +
" into original index or indexes: " + displayedIndexes + "."
});
}
timeline.push({
phase: "complete",
order: sortedPairs.map((pair) => pair.source),
activeSources: [],
output: [...output],
message:
"All ranks are written. Equal values received the same rank, and every larger distinct value received a larger rank."
});
return timeline;
}
function createPairNode(pair) {
const node = document.createElement("div");
node.className = "pair";
node.innerHTML =
'<span class="value"></span>' +
'<span class="meta"></span>';
node.querySelector(".value").textContent = pair.value;
node.querySelector(".meta").textContent = "index " + pair.source;
workLane.appendChild(node);
pairNodes.set(pair.source, node);
}
function buildStaticLanes() {
pairNodes.clear();
outputNodes.clear();
workLane.innerHTML = "";
originalLane.innerHTML = "";
outputLane.innerHTML = "";
if (values.length === 0) {
workLane.innerHTML =
'<div class="empty-state">No work items are needed.</div>';
originalLane.innerHTML =
'<div class="empty-state">The original array is empty.</div>';
outputLane.innerHTML =
'<div class="empty-state">The output array is empty.</div>';
return;
}
for (const pair of inputPairs) {
createPairNode(pair);
}
for (let index = 0; index < values.length; index += 1) {
const originalCell = document.createElement("div");
originalCell.className = "array-cell";
originalCell.innerHTML =
'<span class="index">index ' + index + '</span>' +
'<strong></strong>';
originalCell.querySelector("strong").textContent = values[index];
originalLane.appendChild(originalCell);
const outputCell = document.createElement("div");
outputCell.className = "array-cell";
outputCell.innerHTML =
'<span class="index">index ' + index + '</span>' +
'<strong>?</strong>';
outputLane.appendChild(outputCell);
outputNodes.set(index, outputCell);
}
}
function renderWorkLane(step) {
if (values.length === 0) {
return;
}
const positionBySource = new Map();
step.order.forEach((source, position) => {
positionBySource.set(source, position);
});
workTitle.textContent =
step.phase === "prepare"
? "1. Work lane: input order"
: "1. Work lane: sorted by value";
const laneWidth = Math.max(values.length * 94, 560);
workLane.style.width = laneWidth + "px";
for (const pair of inputPairs) {
const node = pairNodes.get(pair.source);
const position = positionBySource.get(pair.source);
const isActive = step.activeSources.includes(pair.source);
node.style.transform = "translateX(" + (position * 94 + 4) + "px)";
node.classList.toggle("active", isActive);
}
}
function renderOutputLane(step) {
for (let index = 0; index < values.length; index += 1) {
const cell = outputNodes.get(index);
const rank = step.output[index];
const previousRank = lastRenderedOutput[index];
const isActive = step.activeSources.includes(index);
cell.classList.toggle("active", isActive);
cell.classList.toggle("written", rank !== null);
cell.querySelector("strong").textContent = rank === null ? "?" : rank;
// Restart the animation only when a new rank is written.
if (rank !== null && rank !== previousRank) {
cell.classList.remove("just-written");
void cell.offsetWidth;
cell.classList.add("just-written");
}
}
lastRenderedOutput = [...step.output];
}
function updateControls() {
stepCounter.textContent =
"Step " + (currentStep + 1) + " of " + steps.length;
playButton.textContent = isPlaying ? "Pause" : "Play";
backButton.disabled = currentStep === 0;
forwardButton.disabled = currentStep >= steps.length - 1;
}
function render() {
const step = steps[currentStep];
narrative.textContent = step.message;
renderWorkLane(step);
renderOutputLane(step);
updateControls();
}
function stopPlayback() {
isPlaying = false;
clearTimeout(timerId);
timerId = null;
updateControls();
}
function scheduleNextStep() {
if (!isPlaying) {
return;
}
if (currentStep >= steps.length - 1) {
stopPlayback();
return;
}
const speed = Number(speedSlider.value);
const delay = 1300 / speed;
timerId = setTimeout(() => {
currentStep += 1;
render();
scheduleNextStep();
}, delay);
}
function startPlayback() {
if (currentStep >= steps.length - 1) {
currentStep = 0;
lastRenderedOutput = [];
render();
}
isPlaying = true;
updateControls();
scheduleNextStep();
}
function loadArray() {
try {
stopPlayback();
values = parseInput();
inputError.textContent = "";
inputPairs = values.map((value, source) => ({ value, source }));
steps = buildSteps(values);
currentStep = 0;
lastRenderedOutput = [];
buildStaticLanes();
render();
} catch (error) {
inputError.textContent = error.message;
}
}
loadButton.addEventListener("click", loadArray);
playButton.addEventListener("click", () => {
if (isPlaying) {
stopPlayback();
} else {
startPlayback();
}
});
backButton.addEventListener("click", () => {
stopPlayback();
if (currentStep > 0) {
currentStep -= 1;
render();
}
});
forwardButton.addEventListener("click", () => {
stopPlayback();
if (currentStep < steps.length - 1) {
currentStep += 1;
render();
}
});
speedSlider.addEventListener("input", () => {
speedOutput.textContent = Number(speedSlider.value).toFixed(1) + "x";
if (isPlaying) {
clearTimeout(timerId);
scheduleNextStep();
}
});
loadArray();
</script>
</body>
</html>
7. The "Blank Canvas" Industry Scenario:
-
What input sizes, value ranges, and unusual inputs should this feature support?
Ask whether the input can be empty, contain duplicates, include negative values, contain very large numbers, or arrive from an external service.
-
What exactly does “rank” mean for duplicate values and ordering direction?
Confirm whether equal values share a rank, whether ranks must be consecutive, and whether the smallest value should be rank 1 or the largest value should be rank 1.
-
Should this function modify the original array, return a new one, or report invalid input differently?
This defines the input/output agreement, often called a contract: what callers can provide and what they can expect back.