BQN, 99 5 bytes
≡⟜∧·∾´·∧⊔≡⟜∧⊐˜ Anonymous tacit function. Takes a string or a list of integers. Try it at BQN online!Try it at BQN online!
Explanation
The secret sauce here is theInspired by ⊔ Group builtin. In a monadic contextDennis's J answer, it takesthough the indices ofdetails are a list and divides them up intobit different "buckets" based on the value at each index. For example
Given two lists, ⊔ ⟨4,4,1,2,1⟩ gives ⟨⟨⟩,⟨2,4⟩,⟨3⟩,⟨⟩,⟨0,1⟩⟩⊐ works as follows: there are no 0s; there arefor each element of its right argument, it finds the first index of that value in its left argument.
We're using 1⊐˜s at indices 2, which passes the same list as both left and 4; thereright arguments. The result is a 2 atlist, for each digit, of the index 3; there are no 3s; and there are 4s at indices 0 and 1of that digit's first occurrence.
If all occurrences of the same digitdigits are consecutivegrouped together, then sorting these groups of indices will cause all the indices to beoccur in ascending order. OtherwiseHowever, if some indicescopies of digit A are separated by digit B, B's (larger) index will be outcome between the copies of order even after sorting their groupsA's (smaller) index.
≡⟜∧·∾´·∧⊔≡⟜∧⊐˜ ⊐˜ First ⊔index of Groupeach indicesdigit ofin the argument list ·∧ Sort ascending (in lexical order) ·∾´ Fold on concatenate (flatten) ≡⟜ The result is identical to ∧ The result, sorted ascending