question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
check-if-digits-are-equal-in-string-after-operations-i | Python 3 lines, quardratic solution | python-3-lines-quardratic-solution-by-sa-jbxc | IntuitionWe can just simulate step by step where at each step we reduce the number of digits by one.Complexity
Time complexity: O(n2). As each steps takes O(n) | salvadordali | NORMAL | 2025-04-11T07:45:22.829708+00:00 | 2025-04-11T07:45:22.829708+00:00 | 1 | false | # Intuition
We can just simulate step by step where at each step we reduce the number of digits by one.
# Complexity
- Time complexity: $O(n^2)$. As each steps takes $O(n)$
- Space complexity: $O(n)$
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
digits = [int(c) for c in s]
while len(digits) != 2:
digits = [(digits[i] + digits[i + 1]) % 10 for i in range(len(digits) - 1)]
return digits[0] == digits[1]
``` | 0 | 0 | ['Python3'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Simplest C++ Solution | simplest-c-solution-by-0j60pwopfd-yp5p | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | 0j60PWOPfD | NORMAL | 2025-04-10T22:05:48.244802+00:00 | 2025-04-10T22:05:48.244802+00:00 | 1 | false | # Intuition
# Approach
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while (s.size()>= 2) {
if(s.size()== 2){
if(s[0] == s[1])
return true;
}
string s1;
for(int i = 0; i<s.size()-1; i++){
s1 += (s[i] + s[i+1]) % 10;
}
s = s1;
}
return false;
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Optimized simple solution - beats 100%🔥 | optimized-simple-solution-beats-100-by-c-kky1 | Complexity
Time complexity: O(N)
Space complexity: O(N)
Code | cyrusjetson | NORMAL | 2025-04-10T10:45:17.682827+00:00 | 2025-04-10T10:45:36.760893+00:00 | 2 | false | # Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
int[] digits = new int[s.length()];
int distance = s.length();
for (int i = 0; i < distance; i++) digits[i] = s.charAt(i) - '0';
while (distance > 2) {
int temp = (distance--) - 1;
for (int i = 0; i < temp; i++) digits[i] = (digits[i] + digits[i + 1]) % 10;
}
return digits[0] == digits[1];
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | easy stringbuilder solution (java) | easy-stringbuilder-solution-java-by-dpas-2z8v | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | dpasala | NORMAL | 2025-04-09T03:10:16.629839+00:00 | 2025-04-09T03:10:16.629839+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
int n = s.length();
while (n > 2) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n - 1; i++) {
int sum = (int)(s.charAt(i) - '0') + (int)(s.charAt(i + 1) - '0');
sb.append(sum % 10);
}
s = sb.toString();
n = sb.length();
}
return s.charAt(0) == s.charAt(1);
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Python Solution -0(n) | python-solution-0n-by-vini__7-h81j | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Vini__7 | NORMAL | 2025-04-08T07:05:57.773571+00:00 | 2025-04-08T07:05:57.773571+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
a=list(map(int,str(s)))
while len(a)!=2:
i=0
c=[]
while(i+1)<len(a):
c.append((a[i]+a[i+1])%10)
i+=1
a=c
return a[0]==a[1]
``` | 0 | 0 | ['Python3'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Java | Recursion approach | Beats 90% | java-recursion-approach-beats-90-by-igor-r928 | Code | IgorChurakov | NORMAL | 2025-04-07T07:49:37.973381+00:00 | 2025-04-07T07:49:37.973381+00:00 | 1 | false | # Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
var chars = new ArrayList<Integer>();
for (int i = 0; i < s.length(); i++) {
chars.add(s.charAt(i) - '0');
}
return hasSameDigits(chars);
}
boolean hasSameDigits(ArrayList<Integer> chars) {
if (chars.size() == 2) {
return chars.get(0) == chars.get(1);
} else {
var newChars = new ArrayList<Integer>();
for (int i = 0; i < chars.size() - 1; i++) {
newChars.add((chars.get(i) + chars.get(i + 1)) % 10);
}
return hasSameDigits(newChars);
}
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Java Intermediate Solution | java-intermediate-solution-by-trevorkmci-9xrv | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | trevorkmcintyre | NORMAL | 2025-04-07T01:16:17.948693+00:00 | 2025-04-07T01:16:17.948693+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public static boolean hasSameDigits(String s) {
String newStr = "";
while(s.length() > 2){
StringBuilder builder = new StringBuilder();
for(int i = 0; i<s.length()-1; i++){
builder.append((s.charAt(i)-48 + s.charAt(i+1)-48)%10);
}
newStr = builder.toString();
s = newStr;
}
return newStr.charAt(0) == newStr.charAt(1);
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Fastest way - infinite loop | fastest-way-infinite-loop-by-zemamba-6ix5 | null | zemamba | NORMAL | 2025-04-06T22:25:22.399898+00:00 | 2025-04-06T22:25:22.399898+00:00 | 1 | false | ```javascript []
/**
* @param {string} s
* @return {boolean}
*/
var hasSameDigits = function(s) {
arr = [...s]
while (arr.length > 2) {
arr = newDigit(arr)
}
return arr[0] == arr[1]
};
function newDigit(ar) {
temp = []
for (let i = 0; i < ar.length - 1; i++) {
temp.push((~~ar[i] + ~~ar[i+1]) % 10)
}
return temp
}
``` | 0 | 0 | ['JavaScript'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | s.compactMap{$0.wholeNumberValue} | scompactmap0wholenumbervalue-by-victor-s-kkaj | null | Victor-SMK | NORMAL | 2025-04-06T17:56:00.311048+00:00 | 2025-04-06T17:56:00.311048+00:00 | 1 | false |
```swift []
class Solution {
func hasSameDigits(_ s: String) -> Bool {
var arr = s.compactMap{$0.wholeNumberValue}
while arr.count > 2 {
for i in 1..<arr.count {
arr[i-1] = (arr[i-1] + arr[i]) % 10
}
arr.removeLast()
}
return arr[0] == arr[1]
}
}
``` | 0 | 0 | ['Math', 'String', 'Swift', 'Python', 'Python3'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Kotlin Solution | kotlin-solution-by-osagiog-9j3t | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | osagiog | NORMAL | 2025-04-06T12:51:51.169889+00:00 | 2025-04-06T12:51:51.169889+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```kotlin []
class Solution {
fun hasSameDigits(s: String): Boolean {
var current=s
while (current.length >2){
current=getStringValues(current)
}
return current[0] == current[1]
}
private fun getStringValues(s:String) : String{
val sb=StringBuilder()
for (i in 0 until s.length - 1) {
val sum = (s[i] - '0') + (s[i + 1] - '0')
sb.append(sum % 10)
}
return sb.toString()
}
}
``` | 0 | 0 | ['Kotlin'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Simple C simluation 100% runtime 94.97% memory | simple-c-simluation-100-runtime-9497-mem-0s1j | IntuitionOkay so.... we need to repeatedly modify the string by replacing adjacent digits with their sum modulo 10 until the string length reduces to exactly 2 | PerryThePpatypus | NORMAL | 2025-04-06T01:01:45.856795+00:00 | 2025-04-06T01:02:57.253994+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Okay so.... we need to repeatedly modify the string by replacing adjacent digits with their sum modulo 10 until the string length reduces to exactly 2 characters. At that point, we check if those two characters are the same.
Instead of allocating new memory at each step, we modify the string in place using a pointer. This way, we avoid unnecessary space allocations and memory management (like freeing memory), making the approach more efficient. ( yipppee pointers -(๑☆‿ ☆#)ᕗ )
The problem description tells us that the initial string is longer than the desired size, so we don’t need to check edge cases related too-short strings.
Given its repetitive operations on the string, recursion seems like a natural approach. We’ll keep reducing the size of the string with each recursive call until it’s reduced to two characters. In each step, we add adjacent digits, take the modulo 10, and update the string in place. The recursive calls will stop once we have exactly 2 characters, and at that point, we’ll compare them to determine if they’re the same.
# Approach
<!-- Describe your approach to solving the problem. -->
Here is a simple summary of what the code is doing:
Base Case: When the string has 2 characters, check if they are equal.
Recursive Case: Iterate through the string,
modify adjacent digits in place,
reduce the string size,
and call the function recursively with the 'updated' string.
# Complexity
- Time complexity: $$O(n^2)$$ (though its more like $$O(\frac{n(n-1)}{2})$$)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$ (* We can probably reduce this by using a while loop instead, because recusive call build up on the stack but to lazy to do that :p *)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
bool hasSameDigits(char* s) {
if (*(s + 2) == '\0') return s[0] == s[1];
char* holder = s;
while (*(holder + 1) != '\0') {
(*holder) = (((*holder - '0') + (*(holder + 1) - '0')) % 10) + '0';
holder++;
}
*(holder) = '\0';
return hasSameDigits(s);
}
``` | 0 | 0 | ['C'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | C# | Simulation | c-simulation-by-we6mmvl7tl-n90w | Complexity
Time complexity: O(n2)
Space complexity: O(1)
Code | we6MMvL7tl | NORMAL | 2025-04-04T13:54:23.080282+00:00 | 2025-04-04T13:54:23.080282+00:00 | 3 | false | # Complexity
- Time complexity: $$O(n^2)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public bool HasSameDigits(string s) {
while (s.Length != 2)
{
string temp = "";
for (int i = 0; i < s.Length -1; i++)
{
temp += (s[i] + s[i+1]) % 10 ;
}
s = temp;
}
if(s[0] == s[1])
return true;
return false;
}
}
``` | 0 | 0 | ['Simulation', 'C#'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Check If Digits Are Equal in String After Operations I in Java | check-if-digits-are-equal-in-string-afte-f3tj | Code | sowmy3010 | NORMAL | 2025-04-02T11:26:03.410988+00:00 | 2025-04-02T11:26:03.410988+00:00 | 1 | false |
# Code
```java []
class Solution {
public String Modulo(String s){
String st="";
for(int i=1;i<s.length();i++){
char ch1 = s.charAt(i-1);
char ch2 = s.charAt(i);
int p = (ch1-'0'+ch2-'0')%10;
st+=p;
}
return st;
}
public boolean hasSameDigits(String s) {
while(s.length()!=2){
s=Modulo(s);
}
return s.charAt(0)==s.charAt(1);
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Checking if a Number Reduces to Two Identical Digits | checking-if-a-number-reduces-to-two-iden-wlaq | IntuitionThe problem requires checking if a given string of digits, when repeatedly transformed by replacing adjacent pairs with their sum modulo 10, eventually | Nylrem | NORMAL | 2025-03-31T20:36:10.834163+00:00 | 2025-03-31T20:36:10.834163+00:00 | 1 | false |
## Intuition
The problem requires checking if a given string of digits, when repeatedly transformed by replacing adjacent pairs with their sum modulo 10, eventually reduces to two identical digits.
## Approach
1. **Iterative Transformation**:
- Start with the given string `s`.
- Repeatedly form a new string by summing adjacent digits modulo 10.
- Continue this process until only two digits remain.
2. **Final Check**:
- If the two remaining digits are equal, return `true`; otherwise, return `false`.
## Complexity
- **Time Complexity**: \(O(n^2)\), as each transformation step reduces the length by 1, leading to a total of \(O(n)\) steps, and each step requires \(O(n)\) operations.
- **Space Complexity**: \(O(n)\), due to the storage of intermediate strings during transformation.
## Code
```java
class Solution {
public boolean hasSameDigits(String s) {
while (s.length() > 2) {
String st = "";
for (int i = 0; i < s.length() - 1; i++) {
int m = Character.getNumericValue(s.charAt(i));
int n = Character.getNumericValue(s.charAt(i + 1));
st += ((m + n) % 10);
}
s = st;
}
return s.charAt(0) == s.charAt(1);
}
}
```
## Optimizations
- **StringBuilder Instead of String Concatenation**: Using `StringBuilder` instead of `st +=` reduces time complexity from \(O(n^2)\) to \(O(n)\) per iteration.
- **In-Place Modification**: Using an integer array instead of strings could further optimize memory usage.
Would you like me to rewrite the code with these optimizations? 🚀 | 0 | 0 | ['Java'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | my solution | my-solution-by-leman_cap13-574e | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | leman_cap13 | NORMAL | 2025-03-30T19:02:15.010852+00:00 | 2025-03-30T19:02:15.010852+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
while len(s)>2:
result = ''
for i in range(len(s)-1):
a=(int(s[i])+int(s[i+1])) % 10
result+=str(a)
s=result
return s[0]==s[1]
``` | 0 | 0 | ['Python3'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Scala solution with implicit, recursion and pattern matching | scala-solution-with-implicit-recursion-a-k30z | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | iyIeO99AmH | NORMAL | 2025-03-29T23:47:52.669218+00:00 | 2025-03-29T23:47:52.669218+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```scala []
object Solution {
def hasSameDigits(s: String): Boolean = {
val array = s.toCharArray
array match {
case Array(v1, v2) =>
v1 == v2
case array: Array[Char] =>
hasSameDigits(sumDigits(array, Array[Char]()).mkString(""))
}
}
def sumDigits(array: Array[Char], result: Array[Char]): Array[Char] = {
array match {
case Array(_) =>
result
case Array(v1, v2, tail @ _*) =>
val value = ((v1.asNum + v2.asNum) % 10).asChar
sumDigits((v2 +: tail).toArray, result :+ value)
}
}
implicit class ConvertToNum(c: Char) {
def asNum: Int = c - '0'
}
implicit class ConvertToChar(i: Int) {
def asChar: Char = (i + '0').toChar
}
}
``` | 0 | 0 | ['Scala'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Solution using extra space with JS | solution-using-extra-space-with-js-by-be-e6ei | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | bek-shoyatbek | NORMAL | 2025-03-29T19:33:01.811139+00:00 | 2025-03-29T19:33:01.811139+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
/**
* @param {string} s
* @return {boolean}
*/
var hasSameDigits = function(s) {
let digits = s.split("").map(Number);
let temp = [];
while(digits.length>2){
for(let i=0;i<digits.length-1;i++){
const mod = (digits[i] + digits[i+1])%10;
temp.push(mod);
}
digits = temp;
temp = [];
}
return digits[0] ==digits[1];
};
``` | 0 | 0 | ['JavaScript'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Simple C++ Solution using queue. | simple-c-solution-using-queue-by-optimiz-yddk | Complexity
Time complexity:
O(n)
Space complexity:
O(n)
Code | OptimizingCompiler | NORMAL | 2025-03-29T10:44:19.908531+00:00 | 2025-03-29T10:44:19.908531+00:00 | 3 | false | # Complexity
- Time complexity:
$$O(n)$$
- Space complexity:
$$O(n)$$
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
deque<int> q;
for (char c : s) {
q.push_back(c - '0');
}
int n = 0;
int c = q.size();
while (q.size() > 2) {
if (--c) {
n = q.front();
q.pop_front();
q.push_back((n + q.front()) % 10);
} else {
q.pop_front();
c = q.size();
}
}
return q.front() == q.back();
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Simple Swift Solution | simple-swift-solution-by-felisviridis-qjyc | Code | Felisviridis | NORMAL | 2025-03-25T09:51:01.184421+00:00 | 2025-03-25T09:51:01.184421+00:00 | 2 | false | 
# Code
```swift []
class Solution {
func hasSameDigits(_ s: String) -> Bool {
var digits = s.compactMap(\.wholeNumberValue)
while digits.count > 2 {
digits = digitsSum(digits)
}
return digits[0] == digits[1]
}
private func digitsSum(_ digits: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<digits.count - 1 {
result.append((digits[i] + digits[i + 1]) % 10)
}
return result
}
}
``` | 0 | 0 | ['Swift'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Go | go-by-stuu-7m0i | Code | stuu | NORMAL | 2025-03-23T01:48:21.827964+00:00 | 2025-03-23T01:48:21.827964+00:00 | 3 | false | 
# Code
```golang []
func hasSameDigits(s string) bool {
operationResult := s
for {
operationResult = reduceDigit(operationResult)
if len(operationResult) == 2 {
break
}
}
if operationResult[0] == operationResult[1] {
return true
}
return false
}
func reduceDigit(s string) string {
baseRune := '0' // use this to convert runes to int
var newDigitString strings.Builder
for i := 0; i < len(s)-1; i++ {
curDig := ((int(s[i] - byte(baseRune))) + int(s[i+1]-byte(baseRune))) % 10
newDigitString.WriteString(strconv.Itoa(curDig))
}
return newDigitString.String()
}
``` | 0 | 0 | ['Go'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | C++ Solution | c-solution-by-chandreyee_12-uaqy | Code | chandreyee_12 | NORMAL | 2025-03-22T15:50:14.666810+00:00 | 2025-03-22T15:50:14.666810+00:00 | 5 | false |
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while(s.size()>2)
{
string str="";
for(int i=0;i<s.size()-1;i++)
{
int x=s[i]-'0';
int y=s[i+1]-'0';
int sum=(x+y)%10;
char ch=sum+'0';
str+=ch;
}
s=str;
}
if(s[0]==s[1]) return true;
else return false;
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Update the list in place, 93% speed | update-the-list-in-place-93-speed-by-evg-zx83 | Code | evgenysh | NORMAL | 2025-03-22T12:59:59.911040+00:00 | 2025-03-22T12:59:59.911040+00:00 | 2 | false | # Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
lst = list(map(int, s))
for end in range(len(lst) - 1, 1, -1):
for i in range(end):
lst[i] = (lst[i] + lst[i + 1]) % 10
return lst[0] == lst[1]
``` | 0 | 0 | ['Python3'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Easy Java Solution for Beginners | easy-java-solution-for-beginners-by-ther-u0ad | Upvote PleaseApproachComplexity
Time complexity:
Space complexity:
Code | therajnishraj | NORMAL | 2025-03-21T05:42:39.452279+00:00 | 2025-03-21T05:42:39.452279+00:00 | 3 | false | # Upvote Please

# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
char[] chararr=s.toCharArray();
StringBuilder sb=new StringBuilder(s);
while(sb.length()>2){
sb=new StringBuilder();
for(int i=0;i<chararr.length-1;i++){
int digit=(Integer.parseInt(chararr[i]+"")+Integer.parseInt(chararr[i+1]+""))%10;
sb.append(digit);
}
chararr=sb.toString().toCharArray();
}
return checksame(sb.toString());
}
public boolean checksame(String s){
int[] hash=new int[10];
for(char ch:s.toCharArray()){
hash[Integer.parseInt(ch+"")]++;
}
int count=0;
for(int i=0;i<hash.length;i++){
if(hash[i]>0)
count++;
}
return count>1?false:true;
}
}
``` | 0 | 0 | ['Hash Table', 'Java'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Easy In-Place Solution | easy-in-place-solution-by-j_cox-9qpy | IntuitionApproach
Loop through S until it has 2 characters
On each loop, take pairs of chars, convert them to int
Perform the operation of adding them and modul | J_Cox | NORMAL | 2025-03-20T16:03:05.019220+00:00 | 2025-03-20T16:03:05.019220+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
1. Loop through S until it has 2 characters
2. On each loop, take pairs of chars, convert them to int
3. Perform the operation of adding them and modulo by 10
4. Replace the first of the two digits with this new value
5. Repeat until last pair of digits.
6. Resize string to fit only new values (cuts off last value each operation)
7. Check if last two values are equal
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
while (s.size() > 2)
{
for (int i = 1; i < s.size(); i++)
{
s[i-1] = ((s[i-1] - '0') + (s[i] - '0')) % 10;
}
s.resize(s.size()-1);
}
return s[0] == s[1];
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | True subquadratic complexity using a bit of number theory :) | true-subquadratic-complexity-using-a-bit-zug9 | ApproachThere is a closed form for the two final digits - they are given by summing digits of s multiplied by binomial coefficients, similar to Pascal's triangl | user5094uY | NORMAL | 2025-03-19T17:58:22.537458+00:00 | 2025-03-19T17:58:22.537458+00:00 | 2 | false | # Approach
There is a closed form for the two final digits - they are given by summing digits of `s` multiplied by binomial coefficients, similar to Pascal's triangle.
This can be leveraged to get log-linear time complexity and logarithmic space complexity. This is a situation where we can't just assume all arithmetic operations take constant time, since central binomial coefficients grow exponentially as $n \to \infty$. Some care is required - computing all full binomial coefficients necessarily takes superlinear time, as the space to even store them all is superlinear in $|s|$.
Luckily, we only need them modulo $10$. We can generate them all mod $10$ using a bit of number-theoretic fiddling, writing each binomial coefficient in the form $2^a \cdot 5^b \cdot m$ where $m$ is coprime to $10$.
This approach scales well to very large inputs. Here are some benchmarks:
| $\lvert s \rvert$ | Time |
| ---------------------|------------------ |
| 10 | 8.6 μs ± 105 ns |
| 100 | 104 μs ± 628 ns |
| 1000 | 1.13 ms ± 3.22 μs |
| 10000 | 12 ms ± 41.7 μs |
| 100000 | 123 ms ± 1.58 ms |
| 1000000 | 1.22 s ± 16.3 ms |
| 10000000 | 12.4 s ± 47.5 ms |
# Complexity
- Time complexity: $\mathcal O(\lvert s \rvert \log^2 \lvert s \rvert)$ is the easiest bound I can see for this algorithm. Probably this analysis can be tightened by exploiting the scarcity of large powers of $2$ or $5$.
- Space complexity: $\mathcal O(\log \lvert s \rvert)$
# Code
```python3 []
# generate all binomial coefficients C(n, k) mod 10
def binoms_mod10(n):
a = b = 0
m = 1
yield 1
for j in range(1, n + 1):
# morally, `m = m * (n + 1 - j) / j`
pa, pb, mm = decompose(n + 1 - j)
ma, mb, dm = decompose(j)
a += pa - ma
b += pb - mb
m = m * mm * pow(dm, -1, 10) % 10
yield m * pow(2, a, 10) * pow(5, b, 10) % 10
# write k in the form 2^a 5^b m, with m coprime to 10
def decompose(k):
a = b = 0
while k % 2 == 0:
k //= 2
a += 1
while k % 5 == 0:
k //= 5
b += 1
return a, b, k
class Solution:
def hasSameDigits(self, s: str) -> bool:
s1 = s2 = 0
for binom, (a, b) in zip(binoms_mod10(len(s) - 2), pairwise(map(int, s))):
s1 += binom * a
s2 += binom * b
return (s1 - s2) % 10 == 0
```
Since we actually know the input is guaranteed to be tiny, we can solve it very very quickly by just pre-computing a table of all binomial coefficients mod $10$. We need to do a bit of compression to make it small enough to submit.
```python3 []
tab=[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,0,0,5,1],[1,6,5,0,5,6,1],[1,7,1,5,5,1,7,1],[1,8,8,6,0,6,8,8,1],[1,9,6,4,6,6,4,6,9,1],[1,0,5,0,0,2,0,0,5,0,1],[1,1,5,5,0,2,2,0,5,5,1,1],[1,2,6,0,5,2,4,2,5,0,6,2,1],[1,3,8,6,5,7,6,6,7,5,6,8,3,1],[1,4,1,4,1,2,3,2,3,2,1,4,1,4,1],[1,*[5]*4,3,*[5]*4,3,*[5]*4,1],[1,6,*[0]*3,8,8,*[0]*3,8,8,*[0]*3,6,1],[1,7,6,0,0,8,6,8,0,0,8,6,8,0,0,6,7,1],[1,8,3,6,0,8,4,4,8,0,8,4,4,8,0,6,3,8,1],[1,9,1,9,6,8,2,8,2,8,8,2,8,2,8,6,9,1,9,1],[1,*[0]*3,5,4,*[0]*4,6,*[0]*4,4,5,*[0]*3,1],[1,1,0,0,5,9,4,*[0]*3,6,6,*[0]*3,4,9,5,0,0,1,1],[1,2,1,0,5,4,3,4,0,0,6,2,6,0,0,4,3,4,5,0,1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3,4,4,*[0]*3,6,6,*[0]*3,4,4,*[0]*3,6,1],[1,7,6,0,0,4,8,4,0,0,6,2,6,0,0,4,8,4,0,0,6,2,6,0,0,8,6,8,0,0,2,4,7,5,0,8,6,8,0,0,2,4,2,0,0,8,6,8,0,0,8,6,8,0,0,2,4,2,0,0,8,6,8,0,5,7,4,2,0,0,8,6,8,0,0,6,2,6,0,0,4,8,4,0,0,6,2,6,0,0,4,8,4,0,0,6,7,1],[1,8,3,6,0,4,2,2,4,0,6,8,8,6,0,4,2,2,4,0,6,8,8,6,0,8,4,4,8,0,2,6,1,2,5,8,4,4,8,0,2,6,6,2,0,8,4,4,8,0,8,4,4,8,0,2,6,6,2,0,8,4,4,8,5,2,1,6,2,0,8,4,4,8,0,6,8,8,6,0,4,2,2,4,0,6,8,8,6,0,4,2,2,4,0,6,3,8,1]]
class Solution:
def hasSameDigits(self, s: str) -> bool:
s1 = s2 = 0
for binom, (a, b) in zip(tab[len(s) - 2], pairwise(map(int, s))):
s1 += binom * a
s2 += binom * b
return (s1 - s2) % 10 == 0
``` | 0 | 0 | ['Python3'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Using Character Array and HashMap | using-character-array-and-hashmap-by-hem-mlet | IntuitionUsing Character Array and HashMapApproachIterative Transformation:The while loop runs until the length of s is reduced to 2.
In each iteration, calcula | hemu1116 | NORMAL | 2025-03-18T17:14:18.241757+00:00 | 2025-03-18T17:14:18.241757+00:00 | 3 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Using Character Array and HashMap
# Approach
<!-- Describe your approach to solving the problem. -->
Iterative Transformation:
The while loop runs until the length of s is reduced to 2.
In each iteration, calculateNewS(s, n) is called, which generates a new string s by applying the transformation.
Transformation Logic (calculateNewS method):
Iterate through adjacent character pairs in s.
1. To Compute the sum of the two digits, Character.getNumericValue(c[i]) gives the numeric value of that character
2. Store only the last digit of the sum (sum % 10) in a HashMap<Integer, String>.
3. Join the transformed values to form a new string.
4. Return the updated string.
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
int n=s.length();
while(n!=2){
s=calculateNewS(s,n);
n=s.length();
}
if(n==2){
if (s.charAt(0)==s.charAt(1)){
return true;
}
}
return false;
}
private String calculateNewS(String s,int n){
Map<Integer,String> nmap=new HashMap<>();
char[] c=s.toCharArray();
for(int i=0;i<n-1;i++){
Integer sum=Character.getNumericValue(c[i])+Character.getNumericValue(c[i+1]);
nmap.put(i, String.valueOf((sum)%10));
}
return nmap.values().stream().collect(Collectors.joining());
}
}
``` | 0 | 0 | ['Java'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | 0ms Runtime using C Programming Language with Easy String Operations | 0ms-runtime-using-c-programming-language-1hh9 | IntuitionThe problem revolves around transforming a string of digits into a sequence of pairs, repeatedly reducing the length of the string until only two digit | Vivek_Bartwal | NORMAL | 2025-03-15T05:32:23.636762+00:00 | 2025-03-15T05:32:23.636762+00:00 | 9 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
The problem revolves around transforming a string of digits into a sequence of pairs, repeatedly reducing the length of the string until only two digits remain. The main focus is to compute the new digits as the modulo 10 of the sum of consecutive pairs. Once the string is reduced, we check if the final two digits are the same.
# Approach
<!-- Describe your approach to solving the problem. -->
Start with a string s consisting of digits.
Use a loop to repeatedly reduce the string until it has exactly two digits:
For each iteration, calculate the new sequence of digits by summing consecutive digits and taking the result modulo 10.
Replace the old string with the new sequence after computation.
Once the string contains exactly two digits, check if they are the same and return true if they are, or false otherwise.
Memory management is crucial to handle intermediate strings efficiently.

# Complexity
- Time complexity: O(n2)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
#include <string.h>
bool hasSameDigits(char* s) {
while (strlen(s) > 2) {
int n = strlen(s);
char* new_s = (char*)malloc(n * sizeof(char)); // To store the new sequence
int k = 0;
for (int i = 0; i < n - 1; i++) {
new_s[k++] =
((s[i] - '0') + (s[i + 1] - '0')) % 10 + '0'; // Sum modulo 10
}
new_s[k] = '\0'; // Null-terminate the string
strcpy(s, new_s);
free(new_s);
}
return s[0] == s[1];
}
``` | 0 | 0 | ['C'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Easy logic and code | easy-logic-and-code-by-aniketkumarsingh9-mqed | Intuitionchanging the string based on its size that should not get to 2.ApproachIterative Digit ReductionComplexity
Time complexity:
O(n).
Space complexity: | AniketKumarSingh99 | NORMAL | 2025-03-14T13:42:09.234943+00:00 | 2025-03-14T13:42:09.234943+00:00 | 3 | false | # Intuition
changing the string based on its size that should not get to 2.
# Approach
Iterative Digit Reduction
# Complexity
- Time complexity:
O(n).
- Space complexity:
O(1).
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
int size=s.size();
while(size!=2){
vector<int>a;
for(int i=0;i<size;i++){
a.push_back(s[i]-48);
}
s = "";
for(int i=0;i<size-1;i++){
int k = (a[i]+a[i+1]) % 10;
s.push_back(k+48);
}
size=s.size();
}
if(s[0]==s[1]) return true;
return false;
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | SIMPLE C PROGRAM | simple-c-program-by-mr_jaikumar-ot5u | IntuitionApproachComplexity
Time complexity:
0 MS
Space complexity:
Code | Mr_JAIKUMAR | NORMAL | 2025-03-14T05:34:28.155999+00:00 | 2025-03-14T05:34:28.155999+00:00 | 11 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
0 MS
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```c []
bool hasSameDigits(char* s) {
int l=strlen(s),n=l-1,jk;
int arr[n];
for(int i=0;i<l-1;i++)
{
arr[i]=(s[i]+s[i+1])%10;
}
while(n!=2)
{
for(int i=0;i<n-1;i++)
{
arr[i]=(arr[i]+arr[i+1])%10;
}
n--;
}
if(arr[0]==arr[1])
{
return 1;
}
return 0;
}
``` | 0 | 0 | ['C'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Kotlin Imperative Solution | kotlin-imperative-solution-by-curenosm-joib | Code | curenosm | NORMAL | 2025-03-13T14:35:19.032310+00:00 | 2025-03-13T14:35:19.032310+00:00 | 2 | false | # Code
```kotlin []
class Solution {
fun hasSameDigits(s: String): Boolean {
var s = s; var i = 1
while (s.length > 2) {
val str = StringBuilder()
for (i in 1 until s.length)
str.append(
(s[i - 1].digitToInt() + s[i].digitToInt()) % 10
)
i = 1; s = str.toString()
}
return s.first() == s.last()
}
}
``` | 0 | 0 | ['Kotlin'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Easy to understand... | easy-to-understand-by-udisha_1234-rc5v | Code | Udisha_1234 | NORMAL | 2025-03-13T12:52:43.788627+00:00 | 2025-03-13T12:52:43.788627+00:00 | 5 | false |
# Code
```cpp []
class Solution {
public:
bool hasSameDigits(string s) {
string ans = s;
while (ans.size() != 2) {
s = ans;
ans = "";
for (int i = 0; i + 1 < s.size(); i++) {
int a = s[i] - 48;
int b = s[i + 1] - 48;
ans += ((a + b) % 10) + 48;
}
}
return ans[0] == ans[1];
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | simple and easy answer | simple-and-easy-answer-by-shiva135-vk92 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Shiva135 | NORMAL | 2025-03-12T15:07:17.592900+00:00 | 2025-03-12T15:07:17.592900+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
while len(s)!=2:
ans=''
for i in range(len(s)-1):
ans+=str((int(s[i])+int(s[i+1]))%10)
s=ans
return True if s[0]==s[1] else False
``` | 0 | 0 | ['Python3'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | simple | simple-by-diorsalimov2006-15e2 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | diorsalimov2006 | NORMAL | 2025-03-12T07:54:18.446961+00:00 | 2025-03-12T07:54:18.446961+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def hasSameDigits(self, s: str) -> bool:
while len(s) > 2:
n = ""
for i in range(len(s) - 1):
n += str((int(s[i]) + int(s[i + 1])) % 10)
s = n
return s[0] == s[1]
``` | 0 | 0 | ['Python3'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | C++ | c-by-tinachien-nkko | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | TinaChien | NORMAL | 2025-03-12T00:40:31.996732+00:00 | 2025-03-12T00:40:31.996732+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
bool equal(vector<int>& nums){
int sum = nums[0] + nums[1];
for(int i = 2; i < nums.size(); i++){
if(nums[i] + nums[i-1] != sum)
return false;
}
return true;
}
bool hasSameDigits(string s) {
vector<int>Temp;
for(auto ch : s){
Temp.push_back(ch - '0');
}
while(Temp.size() > 2){
if(equal(Temp))
return true;
for(int i = 1; i < Temp.size(); i++){
Temp[i-1] = (Temp[i-1] + Temp[i]) % 10;
}
Temp.pop_back();
}
return false;
}
};
``` | 0 | 0 | ['C++'] | 0 |
check-if-digits-are-equal-in-string-after-operations-i | Java | java-by-soumya_699-5nd6 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Soumya_699 | NORMAL | 2025-03-11T08:47:58.021618+00:00 | 2025-03-11T08:47:58.021618+00:00 | 5 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public boolean hasSameDigits(String s) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i <= s.length(); i++) {
if(i+1<s.length()){
if(s.length()==1){
return false;
}
int x = ((Character.getNumericValue(s.charAt(i)) + Character.getNumericValue(s.charAt(i + 1))) % 10);
builder.append(x);
if (builder.length() == s.length() - 1) {
s = s.replace(s, builder);
if ((s.length() == 2) && (s.chars().distinct().count() == 1)) {
return true;
}
builder = new StringBuilder(builder.toString().replace(builder, ""));
i = -1;
}
}
}
return false;
}
}
``` | 0 | 0 | ['Java'] | 0 |
longest-uploaded-prefix | Python Elegant & Short | Amortized O(1) | Commented | python-elegant-short-amortized-o1-commen-wz9c | \nclass LUPrefix:\n """\n Memory: O(n)\n Time: O(1) per upload call, because adding to the set takes O(1) time, and the prefix\n\t\t\t\t can be incre | Kyrylo-Ktl | NORMAL | 2022-10-01T16:07:49.332700+00:00 | 2022-10-01T18:19:06.617886+00:00 | 3,394 | false | ```\nclass LUPrefix:\n """\n Memory: O(n)\n Time: O(1) per upload call, because adding to the set takes O(1) time, and the prefix\n\t\t\t\t can be increased no more than n times for all n calls to the upload function\n """\n\n def __init__(self, n: int):\n self._longest = 0\n self._nums = set()\n\n def upload(self, video: int) -> None:\n self._nums.add(video)\n # Since the prefix cannot decrease, it is enough for us to increase it\n # until we reach the number that has not yet been added\n while self._longest + 1 in self._nums:\n self._longest += 1\n\n def longest(self) -> int:\n return self._longest\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n | 78 | 2 | ['Python', 'Python3'] | 12 |
longest-uploaded-prefix | Most Easy and Short solution + Meme | most-easy-and-short-solution-meme-by-har-2iuy | Self explanatory solution\n\n\nclass LUPrefix {\n Set<Integer> set;\n int max=0;\n public LUPrefix(int n) {\n set=new HashSet<>();\n }\n p | HarshitMaurya | NORMAL | 2022-10-01T16:00:53.534938+00:00 | 2022-11-01T06:23:08.799523+00:00 | 2,741 | false | **Self explanatory solution**\n\n```\nclass LUPrefix {\n Set<Integer> set;\n int max=0;\n public LUPrefix(int n) {\n set=new HashSet<>();\n }\n public void upload(int video) {\n set.add(video);\n while(set.contains(max+1)) max++;\n }\n public int longest() {\n return max;\n }\n}\n```\n\nmeme :\n\n\n\n***let\'s connect :***\n\n\uD83D\uDE80 [www.linkedin.com/in/harshitmaurya](https://www.linkedin.com/in/harshitmaurya/)\n\uD83D\uDE80 [twitter.com/HarshitMaurya_](https://twitter.com/HarshitMaurya_)\n\n\n\n | 37 | 1 | ['Ordered Set', 'Java'] | 7 |
longest-uploaded-prefix | C++ | Set | Easy Understanding | c-set-easy-understanding-by-kiranpalsing-wh7n | Approach \n- We will insert number in set s.\n- When the longest() function will be called, the set will try to increase the answer by checking the next values. | kiranpalsingh1806 | NORMAL | 2022-10-01T16:04:20.078027+00:00 | 2022-10-01T16:16:32.096928+00:00 | 2,449 | false | **Approach** \n- We will insert number in set `s`.\n- When the `longest()` function will be called, the set will try to increase the answer by checking the next values.\n\n**C++ Code**\n\n```cpp\nclass LUPrefix {\n public:\n set<int> s;\n int t = 0;\n LUPrefix(int n) {\n }\n\n void upload(int video) {\n s.emplace(video);\n }\n\n int longest() {\n while (s.count(t + 1)) {\n t++;\n }\n return t;\n }\n};\n``` | 26 | 4 | ['C'] | 7 |
longest-uploaded-prefix | Java TreeSet (super simple) | java-treeset-super-simple-by-ricola-ba5r | Intuition\nKeep a TreeSet of all the numbers (videos) NOT uploaded yet.\nYou can then look at the lowest not uploaded value, and the prefix is the value just be | ricola | NORMAL | 2022-10-01T16:01:10.469006+00:00 | 2022-10-03T09:46:49.356863+00:00 | 1,025 | false | # Intuition\nKeep a TreeSet of all the numbers (videos) NOT uploaded yet.\nYou can then look at the lowest not uploaded value, and the prefix is the value just before this one.\nSince it\'s a tree, it allows to get the lowest value (leftmost node in the tree) in O(log n)\n\n# Complexity\n- Time complexity:\n - initialization (`new LUPrefix()`) : O(n log n)\n - upload : O(log n)\n - longest : O(log n)\n- Space complexity: O(n)\n\n# Code\n```\nclass LUPrefix {\n \n TreeSet<Integer> tree = new TreeSet<>();\n int n;\n\n public LUPrefix(int n) {\n for (int i = 1; i <= n ; i++) {\n tree.add(i);\n }\n this.n = n;\n }\n\n public void upload(int video) {\n tree.remove(video);\n }\n\n public int longest() {\n return tree.isEmpty() ? n : tree.first() -1;\n }\n}\n```\n\n# Note 1\n\nUsing a priority queue (heap) would have had better complexity (O(n) initialization, O(log n) upload and O(1) longuest) but in Java implementation, removing from a priority queue is O(n) instead of O(log n).\n\n# Note 2\nThis not the optimal solution, the optimal one is the HashSet/array one. However one advantage of the tree solution, is that the worst case of any `upload()` call is `O(log n)` while for the HashSet/array the worst case of one call is `O(n)` (but `O(1)` amortized). | 19 | 1 | ['Java'] | 1 |
longest-uploaded-prefix | ✅C++ | ✅Use Array | ✅Easy approach | c-use-array-easy-approach-by-yash2arma-e07s | \nclass LUPrefix {\npublic:\n \n vector<int> pre;\n int val=0;\n \n LUPrefix(int n) \n {\n pre.resize(n+2, 0);\n }\n \n void u | Yash2arma | NORMAL | 2022-10-01T17:11:30.530961+00:00 | 2022-10-01T17:11:30.531012+00:00 | 1,080 | false | ```\nclass LUPrefix {\npublic:\n \n vector<int> pre;\n int val=0;\n \n LUPrefix(int n) \n {\n pre.resize(n+2, 0);\n }\n \n void upload(int video) \n {\n pre[video] = 1;\n \n }\n \n int longest() \n {\n while(pre[val+1]==1)\n val++;\n \n return val;\n }\n};\n``` | 12 | 0 | ['Array', 'C', 'C++'] | 1 |
longest-uploaded-prefix | Python 3 || iteration || T/S: 97% / 59% | python-3-iteration-ts-97-59-by-spaulding-lg18 | \nclass LUPrefix:\n\n def __init__(self, n: int):\n self.stream = [False]*n\n self.maxLength = n\n self.prefLength = 0\n \n de | Spaulding_ | NORMAL | 2022-10-01T19:06:27.019656+00:00 | 2024-06-15T14:41:14.594046+00:00 | 579 | false | ```\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.stream = [False]*n\n self.maxLength = n\n self.prefLength = 0\n \n def upload(self, video: int) -> None:\n self.stream[video-1] = True\n\n def longest(self) -> int:\n for i in range(self.prefLength,self.maxLength):\n\n if self.stream[i]:\n self.prefLength = i+1\n\n else: break\n\n return self.prefLength\n```\n\n[https://leetcode.com/problems/longest-uploaded-prefix/submissions/1289137170/](https://leetcode.com/problems/longest-uploaded-prefix/submissions/1289137170/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*). | 9 | 0 | ['Python', 'Python3'] | 0 |
longest-uploaded-prefix | ✅✅✅ C++ with Explanation || Very Simple & Easy to Understand Solution | c-with-explanation-very-simple-easy-to-u-s23c | Up Vote if you like the solution \n\n\n/* take an array that keeps a mark of each of the video that uploaded.\n keep another varible - latest, that keeps trac | kreakEmp | NORMAL | 2022-10-01T16:02:18.394646+00:00 | 2022-10-01T16:27:24.477152+00:00 | 898 | false | <b>Up Vote if you like the solution \n```\n\n/* take an array that keeps a mark of each of the video that uploaded.\n keep another varible - latest, that keeps track of all the video that\n has been already uploaded till that point of time.\n Update latest, when the new video uploaded just next to it, also keep \n on checking for next videos if those were updated before or not at the \n same time.\n */\nclass LUPrefix {\npublic:\n vector<bool> isupdated;\n int latest;\n LUPrefix(int n) {\n isupdated.resize(n+1, 0);\n latest = 0;\n }\n \n void upload(int video) {\n isupdated[video] = 1;\n if(latest == video-1){\n while(isupdated[video] == 1 && video < isupdated.size()){\n latest = video;\n video++;\n }\n }\n }\n \n int longest() {\n return latest;\n }\n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n``` | 9 | 0 | [] | 3 |
longest-uploaded-prefix | 3 Solutions: Fenwick Tree or Binary Indexed Tree | Segment Tree | Disjoint Set ADT | 3-solutions-fenwick-tree-or-binary-index-1jvx | This discussion thread includes 3 separate solutions using different data structures namely,\n\n1. Fenwick Tree or Binary Indexed Tree\n2. Segment Tree\n3. Disj | mrtwinklesharma | NORMAL | 2022-10-09T21:18:00.444046+00:00 | 2022-10-09T21:18:48.414730+00:00 | 522 | false | This discussion thread includes 3 separate solutions using different data structures namely,\n\n**1. Fenwick Tree or Binary Indexed Tree\n2. Segment Tree\n3. Disjoint Set**\n\nThe intuition behind fenwick tree and segment tree solution is,\n=> We want to find the Longest Uploaded Prefix,\n=> Let\'s create an array of size n\n=> Let\'s consider 0 at the particular index when the video hasn\'t yet uploaded and 1 as uploaded.\n=> Now the questions boils down to, we are interested in finding the longest consecutive ones starting from 0th index\n=> What if we calculate the prefix sum, to find whether there exist all ones or is there any 0 in that portion, FOR EXAMPLE: In this array [1, 1, 1, 1, 0, 1] if we calculate the prefix sum till 3rd index it would be 4 and also there are only 4 locations till 3rd index hence there are all ones, on the other hand let\'s calculate prefix sum till 5th index, and that would be 5 so if there are 6 locations available and sum is 5 then there must be a 0.\n=> The last explanation is all about the solution of this problem. \n=> We can use segment tree or fenwick tree to maintain the prefix sum and then we can find whether there exists all ones till ith index in just O(logn) time.\n=> In the end it is important to note that there is a need of binary search to find the answer.\n\n\n```\n// Fenwick Tree Solution\nclass LUPrefix {\npublic:\n // `answer` will store the most updated answer at each step\n int answer;\n \n // This is a pointer to the binary indexed tree, we will dynamically allocate an array in constructor\n int *B_I_Tree;\n\n // The information about maximum number of input, needed for utilities of Binary Indexed Tree\n int n;\n \n // Given Constructor\n LUPrefix(int n) {\n\n // Initialize `answer` with 0\n answer = 0;\n\n // Store the value of `n` so that we can use it later in functions\n this->n = n; \n\n // Dynamically allocate an array of size `n + 1`\n B_I_Tree = new int[n+1];\n\n // Fill all the indices with 0\n memset(B_I_Tree, 0, sizeof(int)*(n+1));\n }\n \n //---------------------------Binary Indexed Tree Utilities------------------------------//\n void Update(int i, int value) {\n for(; i<=n ; i+=(i&(-i))){\n B_I_Tree[i] += value;\n }\n }\n int Sum(int i){\n int sum = 0;\n for(; i>0 ; i-=(i&(-i))){\n sum += B_I_Tree[i];\n }\n return sum;\n }\n //--------------------------------------------------------------------------------------//\n \n void upload(int video) { \n // By 0 in binary indexed tree we are indicating that the particular indexed video hasn\'t uploaded yet.\n\n // So for each upload operation, Update the value at `video` index by 1 \n\n Update(video, 1);\n }\n \n int longest() {\n\n // Our answer would always be atleast equal to last answer\n int low = answer;\n\n // And at max it can reach to the total number of videos(n)\n int high = n;\n \n // Run a binary search on possible answers\n while(low<=high){\n int mid = (low + high)/2;\n \n // Check if answer is possible\n if(Sum(mid) == mid){\n // If possible then Update the answer\n answer = mid;\n\n // And search for some higher answers\n low = mid + 1;\n }\n\n // Otherwise move to lower answers \n else {\n high = mid - 1;\n } \n }\n\n //Return the answer\n return answer;\n }\n};\n// @MrTwinkleSharma\n```\n\n\n```\n// Segment Tree Solution\nclass LUPrefix {\npublic:\n // `answer` will store the most updated answer at each step\n int answer;\n \n // This is a pointer to the segment tree, we will dynamically allocate an array in constructor\n int *segmentTree;\n\n // The information about maximum number of input, needed for utilities of Segment Tree\n int n;\n \n // Given Constructor\n LUPrefix(int n) {\n\n // Initialize `answer` with 0\n answer = 0;\n\n // Store the value of `n` so that we can use it later in functions\n this->n = n; \n\n // Dynamically allocate an array of size `n*4`\n segmentTree = new int[n*4];\n\n // Fill all the indices with 0, Because we have no data to separately build the tree\n memset(segmentTree, 0, sizeof(int)*(n*4));\n }\n \n //---------------------------Segment Tree Utilities------------------------------//\n void Update(int index, int start, int end, int updateIndex, int value) {\n // No overlap case\n if(updateIndex < start || updateIndex > end){\n return;\n }\n\n // Update at leaf node\n if(start==end){\n segmentTree[index] = value;\n return;\n }\n\n // Recursively Update both Parts of segment tree\n int mid = (start + end)/2;\n\n Update(2*index + 1, start, mid, updateIndex, value);\n Update(2*index + 2, mid + 1, end, updateIndex, value);\n\n // Update the segment tree\n segmentTree[index] = segmentTree[2*index + 1] + segmentTree[2*index + 2]; \n }\n int Query(int index, int start, int end, int qstart, int qend){\n // No overlap\n if(qend<start || qstart>end){\n return 0;\n }\n\n // Complete Overlap\n if(qstart<=start && qend>=end){\n return segmentTree[index];\n }\n\n int mid = (start + end)/2;\n \n // Recursively find the answer from both subtree\n return Query(2*index+1, start, mid, qstart, qend) + Query(2*index+2, mid+1, end, qstart, qend);\n }\n //--------------------------------------------------------------------------------------//\n \n void upload(int video) { \n // By 0 in segment tree leaf we are indicating that the particular indexed video hasn\'t uploaded yet.\n\n // So for each upload operation, Update the value at `video` index by 1 \n\n // Our segment tree is 0 indexed so use `video - 1` as update index \n Update(0, 0, n-1, video-1, 1);\n }\n \n int longest() {\n\n // Our answer would always be atleast equal to last answer\n int low = answer;\n\n // And at max it can reach to the total number of videos(n)\n int high = n;\n \n // Run a binary search on possible answers\n while(low<=high){\n int mid = (low + high)/2;\n \n // Check if answer is possible\n if(Query(0, 0, n - 1, 0, mid-1) == mid){\n // If possible then Update the answer\n answer = mid;\n\n // And search for some higher answers\n low = mid + 1;\n }\n\n // Otherwise move to lower answers \n else {\n high = mid - 1;\n } \n }\n\n //Return the answer\n return answer;\n }\n};\n// @MrTwinkleSharma\n```\n\n\nThe intuition behind disjoint set solution is, \n=> If we create an array of n and mark the uploaded video as 1 and other as 0, then our goal is to find the maximum length of consecutive ones from starting index.\n=> The same thing we can do with disjoint set, we can create disjoint set and for each `upload` operation we can merge the disjoint sets of `video-1` and `video+1` with `video`. But by making sure that video-1 and video+1 have been already uploaded, we can using any kind of hashing for that purpose.\n=> For each Union operation we will always try to make the lower index as parent so that in the end we can get to know the size of 1st disjoint set.\n=> The size of first disjoint set will give the answer. We can maintain the size of disjoint set with the help of rank by size.\n```\n// Disjoint Set solution\nclass LUPrefix {\npublic:\n // Parent will store the Absolute parent of the Disjoint Set Elements\n // Rank will store the size of each disjoint set\n int *parent, *rankBySize;\n \n // Total number of `video`, needed later so we are storing it in a global variable\n int n;\n \n // A unordered_map to track the uploaded video\n unordered_map<int, int> mp;\n \n \n LUPrefix(int n) {\n \n this->n = n;\n \n // Create the disjoint set array\n parent = new int[n + 1];\n rankBySize = new int[n + 1];\n \n // Build the disjoint set\n for(int i = 1;i<=n;i++){\n parent[i] = i;\n rankBySize[i] = 1;\n }\n }\n \n // Find Utility\n int Find(int node){\n if(parent[node] == node){\n return node;\n }\n parent[node] = Find(parent[node]);\n return parent[node];\n }\n \n // Union\n void Union(int node1, int node2){\n int p1 = Find(node1);\n int p2 = Find(node2);\n \n if(p1 != p2){\n \n // We will always try to merge the parent with higher index into smaller one \n // Because we want our answer to be concentrated at index `1`\n if(p1<p2){\n parent[node2] = node1;\n rankBySize[p1]+=rankBySize[p2];\n }\n else if(p2<p1){\n parent[node1] = node2;\n rankBySize[p2]+=rankBySize[p1];\n }\n }\n }\n \n void upload(int video) {\n // Make union of video with video - 1 and video + 1\n // But make sure that the video - 1 and video + 1 is already uploaded\n if(video-1>=1 && mp[video-1]==1) Union(video, video-1);\n if(video+1<=n && mp[video+1]==1) Union(video, video+1);\n \n // Upload the video\n mp[video] = 1;\n }\n \n int longest() {\n // Return the size of disjoint set having absolute parent `1`.\n // If 1 video has not been uploaded yet, then still rankBySize will give 1\n // So we are checking whether `1` video is uploaded or not, as a base case\n return mp[1] ? rankBySize[1] : 0;\n }\n};\n//@MrTwinkleSharma\n```\n | 8 | 0 | ['Tree', 'Binary Tree'] | 3 |
longest-uploaded-prefix | Java | O(1) time | 1D Array | java-o1-time-1d-array-by-akrchaubey-ndon | ```\nclass LUPrefix {\n \n boolean[] uploaded;\n int max;\n int size;\n public LUPrefix(int n) {\n uploaded = new boolean[n + 1];\n | akrchaubey | NORMAL | 2022-10-01T16:34:13.658878+00:00 | 2022-10-01T16:42:57.339528+00:00 | 775 | false | ```\nclass LUPrefix {\n \n boolean[] uploaded;\n int max;\n int size;\n public LUPrefix(int n) {\n uploaded = new boolean[n + 1];\n max = 0;\n size = n;\n }\n \n public void upload(int video) {\n uploaded[video] = true;\n\t\t\n\t\t/** \n\t\tIf the longest uploaded prefix is not the previous video then \n\t\tthere must be some other video (smaller than current video) which is not uploaded yet \n\t\t*/\n if(max != video - 1) return;\n\t\t\n\t\t/** \n\t\tIf the longest uploaded prefix is the previous video then we can conclude that \n\t\tall the videos before it have been uploaded. \n\t\t\n\t\tNow we need to check all videos (greater than current video) that have been uploaded and form a contigous subarray\n\t\t*/\n while(video <= size && uploaded[video]){\n video++;\n }\n max = video - 1;\n }\n \n public int longest() {\n return max;\n }\n}\n | 8 | 2 | ['Array', 'Java'] | 0 |
longest-uploaded-prefix | Extremely Easy Solution | Vector instead of Set | Linear Solution | extremely-easy-solution-vector-instead-o-5pcz | We can just use a vector and resize it to n to initialize it. We can maintain a global variable named last wihch will tell us the longest video which we can see | modernbeast02 | NORMAL | 2022-10-03T02:14:10.231590+00:00 | 2022-10-03T02:14:10.231624+00:00 | 581 | false | We can just use a vector and resize it to n to initialize it. We can maintain a global variable named last wihch will tell us the longest video which we can see. Total Time Complexity will be O(N) but Amortized Time Complexity will be O(1). If it helped u, don\'t forget to upvote.\uD83D\uDE03\n```\nclass LUPrefix {\n vector<int>v;\n int last = 0;\npublic:\n LUPrefix(int n) {\n v.resize(n);\n }\n \n void upload(int video) { \n v[video - 1] = 1;\n }\n \n int longest() {\n while(last < v.size() && v[last] == 1){\n last++;\n }\n return last;\n }\n};\n``` | 7 | 0 | [] | 0 |
longest-uploaded-prefix | very easy solution ||C++||O(Nlogn) | very-easy-solution-conlogn-by-baibhavkr1-ooh0 | Intuition\nWe will going to use set here because we know that set have element in sorted order\n\n# Approach\nnow i am going to describe my intution using a exa | baibhavkr143 | NORMAL | 2022-10-01T16:03:35.029265+00:00 | 2022-10-01T16:13:24.670707+00:00 | 612 | false | # Intuition\nWe will going to use set here because we know that set have element in sorted order\n\n# Approach\nnow i am going to describe my intution using a example\nlet n=6;\nnow put all element from 1 to 6 in set\ns={1,2,3,4,5,6}\n\nnow when ever the function ***upload*** is called we gonna delete that element from set\nnow lets delete 3\nthen s={1,2,4,5,6}\nanswer will be 0\n\nnow delete 5\nthen s={1,2,4,6}\nanswer will be still 0 because 1 is still present in set\n\nnow delete 1\nthen s={2,4,6}\nanswer =1 \n\nnow delete 2\nthen s={4,6}\nanswer =3\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->Nlog(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(N)\n\n# Code\n```\nclass LUPrefix {\npublic:\n set<int>s;\n int size;\n LUPrefix(int n) {\n for(int i=1;i<=n;i++)\n s.insert(i);\n \n size=n;\n }\n \n void upload(int video) {\n s.erase(video); \n }\n \n int longest() {\n auto it=s.begin();\n if(it==s.end())\n return size;\n \n return *it-1;\n }\n \n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n``` | 7 | 0 | ['Ordered Set', 'C++'] | 2 |
longest-uploaded-prefix | TreeSet | treeset-by-java_programmer_ketan-o0c4 | \n/*\nWe will maintain a sorted set of un-uploaded videos.\nTo handle longest() query just return the first_element of the set -1\nFor uploading videos remove t | Java_Programmer_Ketan | NORMAL | 2022-10-01T16:01:16.135472+00:00 | 2022-10-01T16:01:16.135535+00:00 | 278 | false | ```\n/*\nWe will maintain a sorted set of un-uploaded videos.\nTo handle longest() query just return the first_element of the set -1\nFor uploading videos remove the video from the set\n*/\nclass LUPrefix {\n TreeSet<Integer> set;\n public LUPrefix(int n) {\n this.set = new TreeSet<>();\n for(int i=1;i<=n+1;i++) set.add(i);\n }\n public void upload(int video) {\n set.remove(video);\n }\n public int longest() {\n return set.first()-1;\n }\n}\n\n\n``` | 6 | 2 | [] | 2 |
longest-uploaded-prefix | Disjoint Set || Java | disjoint-set-java-by-abdulazizms-jbau | Intuition\nFirst thing came to my mind was to use a disjoint set since different chains are merged at some point.\n\n\n# Approach\nI want to connect the current | abdulazizms | NORMAL | 2022-10-01T16:10:11.796035+00:00 | 2022-10-01T16:23:42.937746+00:00 | 532 | false | # Intuition\nFirst thing came to my mind was to use a disjoint set since different chains are merged at some point.\n\n\n# Approach\nI want to connect the current index to its left and right and maintain the total size of the chain. Disjoint set is a great candidate.\n\nThis approach can be used to solve this problem too:\n[2382. Maximum Segment Sum After Removals](https://leetcode.com/contest/biweekly-contest-85/problems/maximum-segment-sum-after-removals/)\n\n# Complexity\n- Time complexity: Nlog(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: N\n\n# Code\n```\nclass LUPrefix {\n DisjointSet d;\n\n public LUPrefix(int n) {this.d = new DisjointSet(n);}\n \n public void upload(int video) {\n d.merge(video-1, video);\n d.merge(video+1, video);\n }\n \n public int longest() {\n return d.count.get(1) == null? 0:d.count.get(d.find(1));\n }\n}\nclass DisjointSet{\n int [] parent;\n Map<Integer, Integer> count;\n public DisjointSet(int n){\n this.parent = new int [n+1];\n Arrays.fill(parent, -1);\n this.count = new HashMap<>();\n }\n public void make(int x){\n parent[x] = x;\n count.put(x, 1);\n }\n public int find(int x){\n if(parent[x] == x) return x;\n return parent[x] = find(parent[x]);\n }\n public void merge(int x, int y){\n if(parent[y] == -1) make(y);\n if(x <= 0 || x >= parent.length || parent[x] == -1) return;\n int parX = find(x), parY = find(y); \n if(parX != parY){\n parent[parX] = parY;\n count.put(parY, count.get(parY) + count.get(parX));\n }\n }\n}\n``` | 5 | 0 | ['Java'] | 1 |
longest-uploaded-prefix | 🧽 Java Clean & Simple | Union Find | java-clean-simple-union-find-by-palmas-ala9 | \nclass LUPrefix {\n int[] map;\n\n public LUPrefix(int n) {\n map = new int[n + 1];\n }\n\n public void upload(int video) {\n map[vid | palmas | NORMAL | 2022-10-01T16:41:58.310568+00:00 | 2022-10-01T16:41:58.310606+00:00 | 279 | false | ```\nclass LUPrefix {\n int[] map;\n\n public LUPrefix(int n) {\n map = new int[n + 1];\n }\n\n public void upload(int video) {\n map[video - 1] = find(video);\n }\n\n public int longest() {\n return find(0);\n }\n\n int find(int index) {\n if (map[index] == 0)\n return index;\n map[index] = find(map[index]);\n return map[index];\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
longest-uploaded-prefix | [Python3] Using List || O(1) amortized || 354ms || beats 100% | python3-using-list-o1-amortized-354ms-be-keh0 | Here is a small trick with adding additional False to the list end like indicator of boundary. So we don\'t need to check the boundry in the while loop and got | yourick | NORMAL | 2024-03-09T19:14:47.874518+00:00 | 2024-03-09T19:35:46.554497+00:00 | 104 | false | ###### Here is a small trick with adding additional False to the list end like indicator of boundary. So we don\'t need to check the boundry in the while loop and got additional speed profit.\n`while self.videos[self.prefix]` instead of \n`while self.prefix < len(self.videos) and self.videos[self.prefix]`\n```python3 []\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.videos = [False] * (n + 1)\n self.prefix = 0\n\n def upload(self, video: int) -> None:\n self.videos[video-1] = True\n\n def longest(self) -> int:\n while self.videos[self.prefix]:\n self.prefix += 1\n return self.prefix\n```\n```python3 []\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.videos = [False] * (n + 1)\n self.prefix = 0\n\n def upload(self, video: int) -> None:\n self.videos[video-1] = True\n while self.videos[self.prefix]:\n self.prefix += 1\n\n def longest(self) -> int:\n return self.prefix\n```\n\nThis problem looks very similar to [ 1656. Design an Ordered Stream](https://leetcode.com/problems/design-an-ordered-stream/description/) | 3 | 0 | ['Python', 'Python3'] | 0 |
longest-uploaded-prefix | 98% FASTER || C++ || USE ARRAY || EASY APPROACH | 98-faster-c-use-array-easy-approach-by-y-yarh | \nclass LUPrefix {\npublic:\n int x = 1;\n vector<bool> v;\n LUPrefix(int n) {\n v.resize(100002,false);\n }\n \n void upload(int video | yash___sharma_ | NORMAL | 2023-03-06T05:02:05.969121+00:00 | 2023-03-06T05:02:05.969181+00:00 | 569 | false | ```\nclass LUPrefix {\npublic:\n int x = 1;\n vector<bool> v;\n LUPrefix(int n) {\n v.resize(100002,false);\n }\n \n void upload(int video) {\n v[video] = true;\n while(v[x]==true){\n x++;\n }\n }\n \n int longest() {\n return x-1;\n }\n};\n``` | 3 | 0 | ['Array', 'C', 'C++'] | 0 |
longest-uploaded-prefix | ✅C++ || Easy to understand CODE || SHORT | c-easy-to-understand-code-short-by-abhin-tl9e | \n\n\tclass LUPrefix {\n\t\tpublic:\n\t\t\tvector v;\n\t\t\tint it=0;\n\t\t\tLUPrefix(int n) {\n\t\t\t\tvector temp(n,-1);\n\t\t\t\tv=temp;\n\t\t\t}\n\n\t\t\tvo | abhinav_0107 | NORMAL | 2022-10-01T18:58:03.353364+00:00 | 2022-10-01T18:59:15.520582+00:00 | 906 | false | \n\n\tclass LUPrefix {\n\t\tpublic:\n\t\t\tvector<int> v;\n\t\t\tint it=0;\n\t\t\tLUPrefix(int n) {\n\t\t\t\tvector<int> temp(n,-1);\n\t\t\t\tv=temp;\n\t\t\t}\n\n\t\t\tvoid upload(int video) {\n\t\t\t\tv[video-1]=1;\n\t\t\t\twhile(it<v.size()){\n\t\t\t\t\tif(v[it]==-1) break;\n\t\t\t\t\tit++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint longest() {\n\t\t\t\treturn it;\n\t\t\t}\n\t\t}; | 3 | 0 | ['C', 'C++'] | 0 |
longest-uploaded-prefix | JAVA solution | HashSet | java-solution-hashset-by-sourin_bruh-b73l | Please Upvote !!! (\u25E0\u203F\u25E0)\n\nclass LUPrefix {\n Set<Integer> set;\n int maxConsecutiveVideo = 0;\n \n public LUPrefix(int n) {\n | sourin_bruh | NORMAL | 2022-10-01T18:05:30.507548+00:00 | 2022-10-01T18:05:30.507574+00:00 | 368 | false | ### ***Please Upvote !!!*** **(\u25E0\u203F\u25E0)**\n```\nclass LUPrefix {\n Set<Integer> set;\n int maxConsecutiveVideo = 0;\n \n public LUPrefix(int n) {\n set = new HashSet<>();\n }\n \n public void upload(int video) {\n set.add(video);\n while (set.contains(maxConsecutiveVideo + 1)) {\n maxConsecutiveVideo++;\n }\n }\n \n public int longest() {\n return maxConsecutiveVideo;\n }\n}\n\n// TC: O(1), SC: O(n)\n``` | 3 | 0 | ['Java'] | 0 |
longest-uploaded-prefix | easy implementation O(n) in vector || comments|| beginner friendly | easy-implementation-on-in-vector-comment-lzkw | \tclass LUPrefix {\n private:\n vector v;\n int i;\n\tpublic:\n LUPrefix(int n) {\n v.resize(n+1);\n\t\t//take i from start\n i=0;\n | sjain8078 | NORMAL | 2022-10-01T16:03:35.221525+00:00 | 2022-10-01T17:13:21.977631+00:00 | 218 | false | \tclass LUPrefix {\n private:\n vector<int> v;\n int i;\n\tpublic:\n LUPrefix(int n) {\n v.resize(n+1);\n\t\t//take i from start\n i=0;\n // memset(v.begin(),v.end(),0);\n }\n \n void upload(int video) {\n\t//upload it to the previous index so we can track it\n v[video-1]=1;\n }\n \n int longest() {\n\t// increase the index until we get the empty slot\n while(v[i]==1){\n i++;\n }\n return i;\n }\n}; | 3 | 0 | ['Design', 'C'] | 0 |
longest-uploaded-prefix | Using Segment Tree Approach | using-segment-tree-approach-by-jayush10a-tgdb | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | jayush10ashu | NORMAL | 2024-01-18T21:44:45.770255+00:00 | 2024-01-18T21:44:45.770297+00:00 | 72 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass LUPrefix {\npublic:\n int tot=0;\n vector<bool> tree;\n\n void update(int video,int node,int st,int en)\n {\n if(st==en)\n {\n if(st==video)\n tree[node]=true;\n return;\n }\n int mid=(st+en)/2;\n if(video<=mid)\n update(video,2*node,st,mid);\n else\n update(video,2*node+1,mid+1,en);\n \n tree[node]=tree[2*node]&tree[2*node+1];\n }\n\n int query(int node,int st,int en)\n {\n if(st==en)\n return tree[node]?en:0;\n if(tree[node])\n return en;\n int mid=(st+en)/2;\n return (tree[2*node]==0)? query(2*node,st,mid) : max(mid,query(2*node+1,mid+1,en));\n }\n\n LUPrefix(int n) {\n tot=n;\n tree.resize(4*n);\n }\n\n void upload(int video) {\n update(video,1,1,tot); \n }\n \n int longest() {\n return query(1,1,tot);\n }\n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n``` | 2 | 0 | ['Segment Tree', 'C++'] | 0 |
longest-uploaded-prefix | Easy Solution Using Max & Min Heap | easy-solution-using-max-min-heap-by-shri-0tq5 | \n\n# Code\n\nclass LUPrefix {\npublic:\n priority_queue<int>q;\n priority_queue<int,vector<int>,greater<int>>q2;\n int prev;\n LUPrefix(int n) {\n | Shristha | NORMAL | 2023-02-05T13:08:45.611241+00:00 | 2023-02-05T13:08:45.611273+00:00 | 443 | false | \n\n# Code\n```\nclass LUPrefix {\npublic:\n priority_queue<int>q;\n priority_queue<int,vector<int>,greater<int>>q2;\n int prev;\n LUPrefix(int n) {\n prev=0;\n }\n \n void upload(int video) {\n q.push(video);\n q2.push(video);\n }\n \n int longest() {\n if(!q.empty() && q.size()==q.top())return q.top();\n else if(!q2.empty()){\n int res=prev;\n while(res+1==q2.top()){\n res++;\n q2.pop();\n }\n prev=res; \n return res; \n\n }\n else \n return 0;\n }\n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n``` | 2 | 0 | ['Heap (Priority Queue)', 'C++'] | 0 |
longest-uploaded-prefix | [Python] Union Find | python-union-find-by-coolguazi-w2d8 | \n# Code\n\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.videos = list(range(n + 1))\n self.uploaded = [1] + [0] * (n + 1)\n\n def | coolguazi | NORMAL | 2023-01-30T10:55:56.179039+00:00 | 2023-01-30T10:55:56.179070+00:00 | 73 | false | \n# Code\n```\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.videos = list(range(n + 1))\n self.uploaded = [1] + [0] * (n + 1)\n\n def upload(self, video: int) -> None:\n self.uploaded[video] = 1\n if self.uploaded[video + 1]: self.union(video, video + 1)\n if self.uploaded[video - 1]: self.union(video, video - 1)\n\n def union(self, u, v):\n x, y = self.find(u), self.find(v)\n if x > y: self.videos[y] = x\n elif y > x: self.videos[x] = y\n\n def find(self, u):\n if u == self.videos[u]: return u\n self.videos[u] = self.find(self.videos[u])\n return self.videos[u]\n\n def longest(self) -> int:\n return self.find(0)\n``` | 2 | 0 | ['Union Find', 'Python3'] | 0 |
longest-uploaded-prefix | very simple solution using bitarray | very-simple-solution-using-bitarray-by-d-4nfc | Intuition\nUse an array to keep the indexes of the videos that has been uploaded, and a variable llp (Last Longest Prefix) to keep the last longer prefix\n\n# A | dwluciano | NORMAL | 2022-12-12T20:14:47.667377+00:00 | 2022-12-12T20:15:18.776228+00:00 | 37 | false | # Intuition\nUse an array to keep the indexes of the videos that has been uploaded, and a variable llp (Last Longest Prefix) to keep the last longer prefix\n\n# Approach\nUse bit array to keep the indexes of the uploaded videos, and precalculate the LUP on each upload, this means to loop through the bit array until a non uploaded video is found. \n\n# Complexity\n- Time complexity:\n**Constructor**: $$O(1)$$\n**Upload**: $$O(1)$$\n**Longest**: $$O(1)$$\n\n- Space complexity:\n**Constructor**: $$O(n)$$, one bit per each __ith__ video\n**Upload**: $$O(1)$$\n**Longest**: $$O(1)$$\n\n# Code\n```\npublic class LUPrefix {\n private int llp = 0;\n private readonly BitArray b;\n public LUPrefix(int n) => b = new(n);\n\n public void Upload(int video) {\n if(b[video - 1])\n return;\n b[video - 1] = true;\n while(llp< b.Length && b[llp])\n llp++;\n }\n\n public int Longest() => llp;\n}\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix obj = new LUPrefix(n);\n * obj.Upload(video);\n * int param_2 = obj.Longest();\n */\n``` | 2 | 0 | ['Bit Manipulation', 'C#'] | 0 |
longest-uploaded-prefix | Easiest approach | C++ | Vector | easiest-approach-c-vector-by-yashrajyash-fshv | \nclass LUPrefix {\npublic:\n vector<int> arr;\n int ptr = 0;\n LUPrefix(int n) {\n arr.resize(n, 0);\n }\n \n void upload(int video) { | yashrajyash | NORMAL | 2022-11-04T12:21:27.907972+00:00 | 2022-11-04T12:21:27.908019+00:00 | 30 | false | ```\nclass LUPrefix {\npublic:\n vector<int> arr;\n int ptr = 0;\n LUPrefix(int n) {\n arr.resize(n, 0);\n }\n \n void upload(int video) {\n arr[video-1]++;\n }\n \n int longest() {\n while(ptr < arr.size() && arr[ptr] != 0)\n ptr++;\n return ptr;\n }\n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n``` | 2 | 0 | ['Array', 'C', 'C++'] | 0 |
longest-uploaded-prefix | [JAVA] Three Approaches [ Segment Tree + Binary Search ] [ Union Find] [Array Based] | java-three-approaches-segment-tree-binar-78xe | \n\n# Segment Tree + Binary Search\n\n\nclass LUPrefix {\n int tree [] ;\n int update(int l , int r , int index,int value){\n if(l==r && l==value){ | aniket7419 | NORMAL | 2022-10-02T17:37:30.688751+00:00 | 2022-10-02T17:37:30.688793+00:00 | 179 | false | \n\n# Segment Tree + Binary Search\n```\n\nclass LUPrefix {\n int tree [] ;\n int update(int l , int r , int index,int value){\n if(l==r && l==value){\n tree[index] = 1;\n return 1;\n }\n int mid = (l+r)/2;\n if(r<value || value<l) return tree[index];\n else{\n int left = update(l,mid,2*index+1,value);\n int right = update(mid+1,r,2*index+2,value);\n tree[index]=left+right;\n return tree[index];\n }\n \n }\n \n \n int query(int l ,int r , int index , int a , int b){\n if(a<=l && b>=r)\n return tree[index];\n else if(b<l || a>r) return 0;\n else\n {\n int mid = (l+r)/2;\n int left = query(l,mid,2*index+1,a,b);\n int right = query(mid+1,r,2*index+2,a,b);\n return left+right;\n }\n }\n int n;\n public LUPrefix(int n) {\n tree = new int[4*n];\n this.n = n;\n }\n \n public void upload(int video) {\n update(1,n,0,video);\n }\n \n public int longest() {\n int low = 1;\n int high = n;\n int ans = 0;\n while(low<=high){\n \n int mid = (low + high)/2;\n \n int count = query(1,n,0,1,mid);\n if(count == mid){\n ans = mid;\n low = mid+1;\n }\n else\n {\n high = mid - 1;\n }\n \n }\n return ans;\n \n \n }\n}\n\n```\n\n# Union Find \n\n```\n\nclass LUPrefix {\n int [] parent ;\n\n int find(int a ){\n if(parent[a]==a) return a;\n return parent[a]=find(parent[a]);\n }\n\n void union(int a , int b){\n parent[b]= parent[a];\n }\n\n public LUPrefix(int n) {\n parent = new int[n+1];\n for(int i = 0;i<=n;i++) parent[i] = i;\n }\n \n public void upload(int video) {\n union(video,video-1);\n }\n \n public int longest() {\n return find(0);\n }\n}\n\n\n```\n\n# Array \n\n```\n\nclass LUPrefix {\n \n int marker [] ;\n int current = 0;\n public LUPrefix(int n) {\n marker = new int[n];\n }\n \n public void upload(int video) {\n marker[video-1] = 1;\n }\n \n public int longest() {\n while(current<marker.length && marker[current]==1) current++;\n return current;\n }\n}\n\n```\n\n | 2 | 0 | ['Java'] | 0 |
longest-uploaded-prefix | C++ | Using Vector | Time Complexity - O(N) | Space Complexity - O(N) | c-using-vector-time-complexity-on-space-qnt78 | \nclass LUPrefix {\nprivate:\n int i;\n int n;\n vector<int> nums;\npublic:\n LUPrefix(int N) {\n i = 0;\n n = N+2;\n nums.resi | CPP_Bot | NORMAL | 2022-10-02T01:53:34.025574+00:00 | 2022-10-02T01:53:34.025615+00:00 | 284 | false | ```\nclass LUPrefix {\nprivate:\n int i;\n int n;\n vector<int> nums;\npublic:\n LUPrefix(int N) {\n i = 0;\n n = N+2;\n nums.resize(n, -1);\n }\n \n void upload(int video) {\n nums[video] = 1;\n while(i<n && (nums[i+1]!=-1)){\n i++;\n } \n return;\n }\n \n int longest() {\n return i;\n }\n};\n\n``` | 2 | 0 | ['C'] | 0 |
longest-uploaded-prefix | [Python] Union-Find | python-union-find-by-dazzbourgh-cfpt | When adding an element, it becomes a member of its own set. Then if a video behind it was uploaded, go ahead and union new set with the previous one. Similarly, | dazzbourgh | NORMAL | 2022-10-01T19:51:57.798551+00:00 | 2022-10-01T19:51:57.798590+00:00 | 146 | false | When adding an element, it becomes a member of its own set. Then if a video behind it was uploaded, go ahead and union new set with the previous one. Similarly, if there\'s another set right after it - merge these two, too.\n\n```\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.uploaded = [0] * (n + 1)\n self.n = n\n \n def upload(self, video: int) -> None:\n self.uploaded[video] = video\n if video == 1 or self.uploaded[video - 1] != 0:\n self.uploaded[video - 1] = video\n if video < self.n and self.uploaded[video + 1] != 0:\n self.uploaded[video] = self.uploaded[video + 1]\n \n def _find(self, i):\n if self.uploaded[i] == 0 or self.uploaded[i] == i:\n return self.uploaded[i]\n else:\n self.uploaded[i] = self._find(self.uploaded[i])\n return self.uploaded[i]\n\n def longest(self) -> int:\n return self._find(0)\n```\t | 2 | 0 | ['Union Find', 'Python'] | 0 |
longest-uploaded-prefix | Few Lines of Code That you should See.O(1) | few-lines-of-code-that-you-should-seeo1-bwrtt | \n | abhinaychaturvedi88 | NORMAL | 2022-10-01T17:44:05.114756+00:00 | 2022-10-01T17:50:12.188768+00:00 | 145 | false | \n | 2 | 0 | [] | 0 |
longest-uploaded-prefix | C++ | Easy Understanding | c-easy-understanding-by-coderabhi2308-6bgs | Self Explanatory Solution\n\nclass LUPrefix {\npublic:\n int ans=0;\n vector< int >isUpdated;\n \n LUPrefix( int n ) {\n isUpdated.assign( n+ | CoderAbhi2308 | NORMAL | 2022-10-01T16:33:42.669069+00:00 | 2022-10-01T16:34:56.349959+00:00 | 90 | false | Self Explanatory Solution\n\n```class LUPrefix {\npublic:\n int ans=0;\n vector< int >isUpdated;\n \n LUPrefix( int n ) {\n isUpdated.assign( n+2 , 0 );\n }\n \n void upload( int video ) {\n isUpdated[ video ] = 1;\n while ( isUpdated[ ans + 1 ] == 1 )\n {\n ans++;\n } \n }\n \n int longest() {\n return ans;\n }\n};\n```\n\n**Fenwick Tree based Solution**\n\nUse binary search to find count of elements from 1 to k\n\nif the count == k, this shows that answer can be k or more than that\n\nTo find the count, we use fenwick tree\n\n```class LUPrefix {\npublic:\n vector< int >fen;\n int N;\n void update ( int i )\n {\n while( i < N )\n {\n fen[ i ]++;\n i += ( i&-i );\n }\n }\n int query( int i )\n {\n int ans = 0;\n while( i > 0 )\n {\n ans += fen[i];\n i -= ( i&-i );\n }\n return ans;\n }\n \n LUPrefix( int n ) {\n N = n + 2;\n fen.assign( n + 5 , 0 );\n \n }\n void upload( int video ) {\n update( video );\n }\n int longest() {\n int l = 0, h = N - 1 , ans = 0;\n while(l <= h)\n {\n int m = ( l + h ) / 2;\n if( query( m ) == m )\n {\n ans = m;\n l = m + 1;\n }\n else{\n h = m - 1;\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'Binary Tree'] | 0 |
longest-uploaded-prefix | Python clean | python-clean-by-404akhan-mdny | \n# N2. Longest Uploaded Prefix\nclass LUPrefix:\n def __init__(self, n: int):\n self.arr = [0] * (n + 2)\n self.ans = 0\n\n def upload(self | 404akhan | NORMAL | 2022-10-01T16:17:55.888047+00:00 | 2022-10-01T16:17:55.888075+00:00 | 150 | false | ```\n# N2. Longest Uploaded Prefix\nclass LUPrefix:\n def __init__(self, n: int):\n self.arr = [0] * (n + 2)\n self.ans = 0\n\n def upload(self, video: int) -> None:\n self.arr[video] = 1\n\n def longest(self) -> int:\n # answer only grows up, by 1\n while self.arr[self.ans + 1]:\n self.ans += 1\n return self.ans\n``` | 2 | 0 | [] | 0 |
longest-uploaded-prefix | C++ | Easy to Understand | Using Vector | c-easy-to-understand-using-vector-by-dhe-680l | \nclass LUPrefix {\npublic:\n vector<int> v;\n int maxi=1;\n LUPrefix(int n) \n {\n v.resize(n+2, 0); \n v[0]=1;\n maxi=1;\n | dheerajkarwasra | NORMAL | 2022-10-01T16:16:18.417072+00:00 | 2022-10-01T17:23:05.324226+00:00 | 29 | false | ```\nclass LUPrefix {\npublic:\n vector<int> v;\n int maxi=1;\n LUPrefix(int n) \n {\n v.resize(n+2, 0); \n v[0]=1;\n maxi=1;\n }\n \n void upload(int video) \n {\n v[video]=1; \n while(v[maxi])\n maxi++;\n }\n \n int longest() \n {\n return maxi-1;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
longest-uploaded-prefix | One Liner functions using vectors O(n) solution | one-liner-functions-using-vectors-on-sol-6kre | Explanation :\n1) i(variable) stores the current index upto which video prefixes from 1 to i-1 are all uploades.\n2) If a videos is uploaded while loop wil | Priyanshu_Chaudhary_ | NORMAL | 2022-10-01T16:13:35.320865+00:00 | 2022-10-01T17:19:20.456942+00:00 | 255 | false | Explanation :\n1) i(variable) stores the current index upto which video prefixes from 1 to i-1 are all uploades.\n2) If a videos is uploaded while loop will loop till it gets an unuploaded video \n3) Since all values are being travel only once the time complextity will be O(n).\n\n```\nclass LUPrefix {\npublic:\n int vec[100001]={0};\n int i=1;\n LUPrefix(int n) \n {\n }\n void upload(int video) \n {\n vec[video]=1;\n while(vec[i])i++;\n }\n \n int longest() \n {\n return i-1;\n }\n};\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n``` | 2 | 0 | ['Array', 'C'] | 1 |
longest-uploaded-prefix | ✅✅✅🤓😎O(n) Solution with Most Easy Solution and Question too | on-solution-with-most-easy-solution-and-j0yar | ****Very Simple and Straight Forward Approch\n\n\nclass LUPrefix {\n\n private: vector<bool>server;\n int ind=-1,maxi=0,_n;\n public:\n | abhigupta7049612180 | NORMAL | 2022-10-01T16:06:18.488814+00:00 | 2022-10-01T16:15:50.118838+00:00 | 363 | false | ****Very Simple and Straight Forward Approch\n\n```\nclass LUPrefix {\n\n private: vector<bool>server;\n int ind=-1,maxi=0,_n;\n public:\n LUPrefix(int n) {\n server.resize(n+5,0);\n server[0]=1;\n _n=n;\n }\n \n void upload(int video) {\n server[video]=1;\n if(server[video-1]==1)check();\n }\n \n int longest() {\n return maxi;\n }\n void check(){\n while(maxi<=_n && server[maxi]!=0){\n maxi++;\n }\n maxi--;\n }\n};\n\n``` | 2 | 0 | ['Array', 'C++'] | 1 |
longest-uploaded-prefix | [Python3] One-Pass Solution O(n), Clean & Concise | python3-one-pass-solution-on-clean-conci-18ws | \nclass LUPrefix:\n\n def __init__(self, n: int):\n self.videos = [False] * (n + 1)\n self.ans = 0\n\n def upload(self, video: int) -> None: | xil899 | NORMAL | 2022-10-01T16:03:04.790824+00:00 | 2022-10-01T16:03:04.790864+00:00 | 480 | false | ```\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.videos = [False] * (n + 1)\n self.ans = 0\n\n def upload(self, video: int) -> None:\n self.videos[video] = True\n if video == self.ans + 1:\n while video < len(self.videos):\n if not self.videos[video]:\n break\n self.ans += 1\n video += 1\n\n def longest(self) -> int:\n return self.ans\n``` | 2 | 0 | ['Python', 'Python3'] | 0 |
longest-uploaded-prefix | simple code | streak method | simple-code-streak-method-by-priyanshuhe-pxzu | \nunordered_map<int, int> mp;\n LUPrefix(int n) {\n for(int i=0;i<n;i++)\n mp[i+1] = 0;\n }\n \n void upload(int video) {\n | priyanshuHere27 | NORMAL | 2022-10-01T16:02:34.845581+00:00 | 2022-10-01T16:13:26.254144+00:00 | 33 | false | ```\nunordered_map<int, int> mp;\n LUPrefix(int n) {\n for(int i=0;i<n;i++)\n mp[i+1] = 0;\n }\n \n void upload(int video) {\n int right = video + 1;\n int left = video - 1;\n int rightStreak = 0, leftStreak = 0;\n \n if(mp[right]!=0)\n rightStreak = mp[right];\n if(mp[left]!=0)\n leftStreak = mp[left];\n \n int streak = leftStreak + rightStreak + 1;\n mp[video] = streak;\n mp[right + rightStreak - 1] = streak;\n mp[left - leftStreak + 1] = streak;\n }\n \n int longest() {\n return mp[1];\n }\n``` | 2 | 0 | ['C', 'Java'] | 1 |
longest-uploaded-prefix | C++ | Caching | Beats 98% - TC | c-caching-beats-98-tc-by-ghozt777-6hap | Intuition
use array to keep track of the videos uploaded
use caching to store previous results of longest() function to avoid recalculation
Approach
our DS cont | ghozt777 | NORMAL | 2025-03-25T06:07:11.172885+00:00 | 2025-03-25T06:07:11.172885+00:00 | 26 | false | # Intuition
- use array to keep track of the videos uploaded
- use caching to store previous results of `longest()` function to avoid recalculation
# Approach
- our DS contains a boolean array to store wether the ith video is uploaded or not, variable prefix to keep track of the largest prefix, and another variable to keep track of the total videos uploaded till now
- To find the longest prefix we need to find the first occurance in the `videos` array where the value is 0, i.e the video is not uploaded , if the `ith` element is the smallest index where value of `videos[i] = 0` then `(i-1)` will be the answer.
- For caching: instead of starting from 0 to n each time we start from `prefix` to `n`, because we know that `0 - prefix` is already occupied with `1s` as its the prefix and there is no need to check again as we are not deleting the videos, so we start from `prefix` to look for any `0s` and finally return our answer
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(n)
# Code
```cpp []
class LUPrefix {
vector<int> videos ;
int cnt ;
int prefix ;
public:
LUPrefix(int n) {
this->videos.resize(n+1,0) ;
this->videos[0] = 1 ;
this->cnt = 0 ;
this->prefix = 0 ;
}
void upload(int video) {
this->videos[video] = 1 ;
++cnt ;
}
int longest() {
int i = prefix ;
while(i <= cnt && videos[i] == 1) ++i ;
prefix = i - 1 ;
return prefix ;
}
};
/**
* Your LUPrefix object will be instantiated and called as such:
* LUPrefix* obj = new LUPrefix(n);
* obj->upload(video);
* int param_2 = obj->longest();
*/
``` | 1 | 0 | ['C++'] | 0 |
longest-uploaded-prefix | (beats 95% for time) Segment tree | beats-95-for-time-segment-tree-by-divyan-qgps | Intuition\nwe can check for the left child and update the parent node on the basis of the left child if the left child dont have the node True the irrespective | Divyansh55BE29 | NORMAL | 2024-10-02T11:51:17.495872+00:00 | 2024-10-02T11:51:17.495905+00:00 | 41 | false | # Intuition\nwe can check for the left child and update the parent node on the basis of the left child if the left child dont have the node True the irrespective of the length of the right child and if the left child has a prefix value we can simply add the left and right child for parent value.\n\n# Approach\nSegment tree query updates.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\no(n)\n\n# Code\n```cpp []\n\nclass LUPrefix {\npublic:\n vector<int> t;\n vector<int> a;\n int k;\n LUPrefix(int n) {\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(nullptr);\n std::cout.tie(nullptr);\n k = n;\n t.resize(4*n,0);\n a.resize(n,0);\n tree(0,k-1,0);\n }\n \n void upload(int video) {\n a[video - 1] = 1;\n int v = video-1;\n update(0, 0,k-1,v);\n }\n \n int longest() {\n return t[0];\n }\n\n private:\n void update(int ind , int tl , int tr, int pos)\n {\n if(tl == tr)\n {\n t[ind] = 1;\n return;\n }\n int tm = (tl+tr)/2;\n\n if(pos<=tm)\n {\n update(ind*2+1,tl,tm,pos);\n }\n else\n {\n update(ind*2+2,tm+1,tr,pos);\n }\n t[ind] = comb(t[2*ind+1],t[2*ind+2],tm,tl,tr);\n }\n\n int comb(int l, int r, int mid ,int tl, int tr)\n {\n if(l == mid-tl+1)\n {\n return l+r;\n }\n else\n {\n return l;\n }\n }\n void tree(int tl,int tr,int ind)\n {\n if(tl == tr)\n {\n t[ind] = a[tl];\n }\n else\n {\n int tm = (tl+tr)/2;\n tree(tl,tm,2*ind+1);\n tree(tm+1,tr,2*ind+2);\n t[ind] = comb(t[2 * ind + 1], t[2 * ind + 2], tm,tl, tr);\n }\n }\n};\n\n``` | 1 | 0 | ['Segment Tree', 'C++'] | 0 |
longest-uploaded-prefix | Segment Tree + binary search longest | O(1) time build, upload, O(logn) time logest(), O(n) space. | segment-tree-binary-search-longest-o1-ti-tzhf | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ziegfeld | NORMAL | 2024-06-21T19:22:50.694902+00:00 | 2024-06-21T19:22:50.694918+00:00 | 20 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass LUPrefix {\n vector<int> seg{};\n int n{0};\n void upd(int i, int l, int h, int ind) {\n if (l == h) {\n // assert(i>=0 && i<=4*n + 4);\n seg[i] = 1;\n // cout << "seg[" << i << "] - " << l << " aka " << ind << " -> 1" << endl;\n return;\n }\n int m = (l + h) / 2;\n if (ind <= m) {\n upd(i * 2, l, m, ind);\n } else {\n upd(i * 2 + 1, m + 1, h, ind);\n }\n seg[i] = seg[i * 2] + seg[i * 2 + 1];\n // cout << "seg[" << i << "] - [" << l << "," << h << "] -> " << seg[i] << endl;\n }\n int qpref(int i, int l, int h) {\n if (seg[i] == h - l + 1) {\n return seg[i];\n }\n if (l == h) {\n // cout << "ans pref - seg[" << i << "] - [" << l << "," << h << "] = " << seg[i] << endl;\n return seg[i];\n }\n int m = (l + h) / 2;\n int ans = qpref(i * 2, l, m);\n if (ans == m - l + 1) {\n // how to know 1,2,..,n all uploaded? total is n, aka n - 1 + 1;\n ans += qpref(i * 2 + 1, m + 1, h);\n }\n // cout << "ans pref - [" << l << "," << h << "] = " << ans << endl;\n return ans;\n }\n // int qpref(int i, int l, int h) {\n // if (l == h) {\n // // cout << "ans pref - seg[" << i << "] - [" << l << "," << h << "] = " << seg[i] << endl;\n // return seg[i];\n // }\n // int m = (l + h) / 2;\n // int ans = qpref(i * 2, l, m);\n // if (ans == m - l + 1) {\n // // how to know 1,2,..,n all uploaded? total is n, aka n - 1 + 1;\n // ans += qpref(i * 2 + 1, m + 1, h);\n // }\n // // cout << "ans pref - [" << l << "," << h << "] = " << ans << endl;\n // return ans;\n // }\npublic:\n LUPrefix(int n) {\n seg.resize(4 * n, 0);\n // upd(0, 0, n-1, 0);\n this->n = n;\n }\n\n void upload(int video) { \n assert(n != 0);\n upd(1, 1, n, video); }\n\n int longest() { \n assert(n != 0);\n return qpref(1, 1, n); \n }\n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n``` | 1 | 0 | ['C++'] | 1 |
longest-uploaded-prefix | Python | Union-Find | python-union-find-by-aljipa-9xhf | Code\n\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.prnt = [-1] * n\n self.size = [0] * n\n\n def _find(self, i):\n while | aljipa | NORMAL | 2024-03-10T02:12:54.637166+00:00 | 2024-03-10T02:12:54.637192+00:00 | 9 | false | # Code\n```\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.prnt = [-1] * n\n self.size = [0] * n\n\n def _find(self, i):\n while i != self.prnt[i]:\n i = self._find(self.prnt[i])\n return self.prnt[i]\n \n def _union(self, x, y):\n if x < 0 or y >= len(self.prnt):\n return\n if self.prnt[x] < 0 or self.prnt[y] < 0:\n return\n px, py = self._find(x), self._find(y)\n if px != py:\n self.prnt[py] = px\n self.size[px] += self.size[py]\n\n def upload(self, v: int) -> None:\n v -= 1\n self.prnt[v] = v\n self.size[v] = 1\n self._union(v - 1, v)\n self._union(v, v + 1)\n\n def longest(self) -> int:\n return self.size[0]\n``` | 1 | 0 | ['Python3'] | 0 |
longest-uploaded-prefix | Fenwick Tree Solution || Binary Search || Explained | fenwick-tree-solution-binary-search-expl-3cfj | First Learn Fenwick Tree from here :\nSimple Explanation\nhttps://www.hackerearth.com/practice/notes/binary-indexed-tree-or-fenwick-tree/\nAdvance Versions\nhtt | coder_rastogi_21 | NORMAL | 2024-02-24T13:52:15.923926+00:00 | 2024-06-25T06:39:31.056085+00:00 | 73 | false | # First Learn Fenwick Tree from here :\nSimple Explanation\n[https://www.hackerearth.com/practice/notes/binary-indexed-tree-or-fenwick-tree/]()\nAdvance Versions\n[https://cp-algorithms.com/data_structures/fenwick.html]()\n\n\n# Complexity\n- Time complexity:\nupload function: $$O(log(n))$$ \nlongest function: $$O(log(n) * log(n))$$\n\n- Space complexity: $$O(n)$$ \n\n# Code\n```\nclass LUPrefix {\npublic:\nint n;\nvector<int> BIT;\n\n LUPrefix(int n) {\n this->n = n;\n BIT.resize(n+1); //allocate space to BIT array\n }\n //just a standard Fenwick tree function to update a value \n void update(int i, int delta)\n {\n for(; i<this->BIT.size(); i += (i&-i)) {\n this->BIT[i] += delta;\n }\n }\n //just a standard Fenwick tree function to query till an index\n int query(int i)\n {\n int sum = 0;\n for(; i>0; i -= (i&-i)) {\n sum += this->BIT[i];\n }\n return sum;\n }\n \n void upload(int video) {\n this->update(video,1); //update index = video by 1\n }\n \n int longest() {\n int low = 1, high = this->BIT.size()-1;\n //find largest index where prefix sum till index equals index\n //i.e. all the values from 1 to index are present\n while(low <= high)\n {\n int mid = (low+high)/2;\n if(this->query(mid) == mid) { //if condition satisfies\n low = mid + 1; //look for a larger index\n }\n else {\n high = mid - 1; //otherwise, we have to look for some smaller index\n }\n }\n return high;\n }\n};\n``` | 1 | 0 | ['Binary Search', 'Binary Indexed Tree', 'C++'] | 1 |
longest-uploaded-prefix | [Java] Easy 100% solution | java-easy-100-solution-by-ytchouar-1rkl | java\nclass LUPrefix {\n private boolean[] videos;\n private int maxIdx = 0;\n\n public LUPrefix(int n) {\n this.videos = new boolean[n + 1];\n | YTchouar | NORMAL | 2024-02-21T03:26:45.035628+00:00 | 2024-02-21T03:27:19.382606+00:00 | 191 | false | ```java\nclass LUPrefix {\n private boolean[] videos;\n private int maxIdx = 0;\n\n public LUPrefix(int n) {\n this.videos = new boolean[n + 1];\n }\n \n public void upload(int video) {\n this.videos[video] = true;\n\n while(maxIdx < this.videos.length - 1 && videos[maxIdx + 1])\n maxIdx++;\n }\n \n public int longest() {\n return maxIdx;\n }\n}\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix obj = new LUPrefix(n);\n * obj.upload(video);\n * int param_2 = obj.longest();\n */\n``` | 1 | 0 | ['Java'] | 0 |
longest-uploaded-prefix | Java | Array + Max Value | java-array-max-value-by-tbekpro-k5k5 | Code\n\nclass LUPrefix {\n\n int res;\n int max;\n int[] arr;\n\n public LUPrefix(int n) {\n res = 0;\n max = 0;\n arr = new in | tbekpro | NORMAL | 2023-11-25T14:23:22.935939+00:00 | 2023-11-25T14:23:22.935956+00:00 | 117 | false | # Code\n```\nclass LUPrefix {\n\n int res;\n int max;\n int[] arr;\n\n public LUPrefix(int n) {\n res = 0;\n max = 0;\n arr = new int[n + 1];\n }\n\n public void upload(int video) {\n arr[video]++;\n max = Math.max(video, max);\n if (video == res + 1) {\n res++;\n }\n boolean exists = true;\n for (int i = res; i <= max; i++) {\n if (arr[i] == 0) {\n res = Math.max(i - 1, res);\n exists = false;\n break;\n }\n }\n if (exists) res = max;\n }\n\n public int longest() {\n return res;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
longest-uploaded-prefix | "Python Concise and Efficient | Achieving Amortized O(1) Complexity | Annotated for Clarity" | python-concise-and-efficient-achieving-a-gxtm | Intuition & Approach :\nThe class LUPrefix is designed to efficiently track the longest prefix of consecutive integers. It uses a set _nums to store uploaded vi | aditya0542pandey | NORMAL | 2023-10-28T06:29:00.598004+00:00 | 2023-10-28T06:29:00.598026+00:00 | 7 | false | # Intuition & Approach :\nThe class LUPrefix is designed to efficiently track the longest prefix of consecutive integers. It uses a set _nums to store uploaded videos, and the variable _longest to maintain the length of the longest consecutive prefix.\n\nIn the constructor __init__, it initializes _longest to 0 and creates an empty set _nums.\n\nIn the upload method, when a new video is uploaded, it\'s added to the set. Then, it checks if there\'s a consecutive video in the set that can extend the current prefix. It does this by continuously incrementing _longest until it reaches a number that has not been uploaded. This ensures that the longest prefix is always up to date.\n\nThe longest method simply returns the current value of _longest, representing the length of the longest consecutive prefix.\n\n# Complexity\n- Time: O(1) for init and longest, O(1) amortized for upload. \n- Space: O(n) for distinct videos. \n- Efficiently tracks longest prefix.\n\n# Code\n```\nclass LUPrefix:\n def __init__(self, n: int):\n self._longest = 0\n self._nums = set()\n\n def upload(self, video: int) -> None:\n self._nums.add(video)\n # Increase the prefix until reaching a number that has not been added\n while self._longest + 1 in self._nums:\n self._longest += 1\n\n def longest(self) -> int:\n return self._longest\n\n\n``` | 1 | 0 | ['Python3'] | 0 |
longest-uploaded-prefix | Java Average Time complexity O(1) | java-average-time-complexity-o1-by-milan-f6y4 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | milangupta95 | NORMAL | 2023-08-07T20:10:55.124385+00:00 | 2023-08-07T20:10:55.124407+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass LUPrefix {\n int[] ans;\n int uploadedUpto;\n public LUPrefix(int n) {\n ans = new int[n];\n }\n \n public void upload(int video) {\n ans[video-1] = 1;\n }\n \n public int longest() {\n for(int i=uploadedUpto;i<ans.length;i++) {\n if(ans[i] == 1) {\n uploadedUpto++;\n } else {\n break;\n }\n }\n return uploadedUpto;\n }\n}\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix obj = new LUPrefix(n);\n * obj.upload(video);\n * int param_2 = obj.longest();\n */\n``` | 1 | 0 | ['Java'] | 1 |
longest-uploaded-prefix | Easy Javascript Solution with array - max 731 ms | easy-javascript-solution-with-array-max-kwe5m | ```\nclass LUPrefix{\n constructor(n){\n this.i = 0;\n this.arr = new Array(n);\n //console.log(this.arr);\n }\n / \n * @param {nu | okarademirci | NORMAL | 2022-10-20T17:48:07.868916+00:00 | 2022-10-20T17:48:07.868956+00:00 | 14 | false | ```\nclass LUPrefix{\n constructor(n){\n this.i = 0;\n this.arr = new Array(n);\n //console.log(this.arr);\n }\n /** \n * @param {number} video\n * @return {void}\n */\n upload = function(video) {\n this.arr[video-1] = video;\n }\n\n/**\n * @return {number}\n */\n longest = function() {\n\n for(;this.i<this.arr.length;this.i++){\n if(!this.arr[this.i]){\n return this.i;\n } \n }\n return this.i;\n }\n \n}; | 1 | 0 | [] | 0 |
longest-uploaded-prefix | Java || TreeSet || union Find | java-treeset-union-find-by-lagahuahubro-8co4 | set contains all the videos which are not yet uploaded so smallest number in the TreeSet represent the smallest numbered video that needs to be uploaded.\n\n\nc | lagaHuaHuBro | NORMAL | 2022-10-07T09:42:10.110252+00:00 | 2022-10-07T10:04:03.503252+00:00 | 45 | false | ```set contains all the videos which are not yet uploaded so smallest number in the TreeSet represent the smallest numbered video that needs to be uploaded.```\n\n```\nclass LUPrefix {\n TreeSet<Integer> set = new TreeSet<>();\n public LUPrefix(int n) {\n for (int i = 1; i <= n + 1; i++) {\n set.add(i);\n }\n }\n \n public void upload(int video) {\n set.remove(video);\n }\n \n public int longest() {\n return set.first() - 1;\n }\n}\n```\n```Union Find```\n```\nclass LUPrefix {\n public int find(int a) {\n return a == par[a] ? a : (par[a] = find(par[a]));\n }\n \n public void union(int a, int b) {\n int parA = find(a);\n int parB = find(b);\n if (parA > parB) {\n par[parB] = parA;\n } else {\n par[parA] = parB;\n }\n }\n \n int[] par;\n boolean[] uploaded;\n public LUPrefix(int n) {\n par = new int[n + 2];\n uploaded = new boolean[n + 2];\n uploaded[0]= true;\n for (int i = 0; i < n + 1; i++) {\n par[i] = i;\n }\n }\n \n public void upload(int video) {\n uploaded[video] = true;\n if (uploaded[video - 1]) union(video, video - 1);\n if (uploaded[video + 1]) union(video, video + 1);\n }\n \n public int longest() {\n return find(0);\n }\n} | 1 | 0 | [] | 0 |
longest-uploaded-prefix | Rust, HashSet, O(n) | rust-hashset-on-by-goodgoodwish-pb6k | Only record the current end of the prefix [1..i]. Keep extending it while can be extended.\n\nuse std::collections::HashSet;\n\nstruct LUPrefix {\n points: | goodgoodwish | NORMAL | 2022-10-07T03:53:04.465331+00:00 | 2022-10-07T03:53:04.465366+00:00 | 136 | false | Only record the current end of the prefix [1..i]. Keep extending it while can be extended.\n```\nuse std::collections::HashSet;\n\nstruct LUPrefix {\n points: HashSet<i32>,\n far: i32,\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl LUPrefix {\n\n fn new(n: i32) -> Self {\n Self {\n points: HashSet::new(),\n far: 0\n }\n }\n \n fn upload(&mut self, video: i32) {\n self.points.insert(video);\n while self.points.len() > 0 {\n let post = self.far + 1;\n if self.points.contains(&post) {\n self.far += 1;\n self.points.remove(&post);\n } else {\n break;\n }\n }\n }\n \n fn longest(&self) -> i32 {\n self.far\n }\n}\n``` | 1 | 0 | ['Rust'] | 0 |
longest-uploaded-prefix | C++ || Array | c-array-by-sachin-vinod-h487 | Approch :-\n1.] Here I am going to use a three number which is -1,0,1 which is as follows ( -1 -> not uploded, 0 -> uploaded but not created prefix , 1 -> uploa | Sachin-Vinod | NORMAL | 2022-10-06T11:32:41.360238+00:00 | 2022-10-06T11:32:41.360285+00:00 | 267 | false | **Approch** :-\n1.] Here I am going to use a three number which is -1,0,1 which is as follows ( -1 -> not uploded, 0 -> uploaded but not created prefix , 1 -> uploaded and created bond with prefix ).\n2.] In upload function what i am going to do is if **curr-1th** is connectd with prefix so we can expand prefix from **curr to elm till elm have 0 means already uploaded**.\n3.] Example :- (-1,-1,-1,-1) i.e. no video is uploaded => upload 3rd => (-1,-1,0,-1) => upload 2nd => (-1,0,0,-1) => upload 1 => (1,1,1,-1)\n\n**c++ code**\n```\nint len;\n int dp[1000002];\n int longestpre=0;\n \n LUPrefix(int n) {\n len=n;\n memset(dp,-1,sizeof(dp));\n dp[0]=1;\n }\n \n void upload(int idx) {\n dp[idx]=0;\n \n if(dp[idx-1]==1){\n while(idx<=len && dp[idx]==0){\n longestpre=max(longestpre,idx);\n dp[idx]=1;\n idx++;\n }\n }\n }\n \n int longest() {\n return longestpre;\n }\n\t//code by sachin\n```\n**upvote is solution was helpful** | 1 | 0 | ['Array', 'C', 'C++'] | 0 |
longest-uploaded-prefix | C++ easy and concise solution | c-easy-and-concise-solution-by-sanket070-flpj | Happy Leetcoding !\n\n\nclass LUPrefix {\npublic:\n set<int>st;\n LUPrefix(int n) {\n for(int i=1;i<=n+1;i++)\n {\n st.insert(i); | sanket0708 | NORMAL | 2022-10-06T04:54:49.166637+00:00 | 2022-10-06T04:54:49.166683+00:00 | 61 | false | Happy Leetcoding !\n\n```\nclass LUPrefix {\npublic:\n set<int>st;\n LUPrefix(int n) {\n for(int i=1;i<=n+1;i++)\n {\n st.insert(i);\n }\n }\n \n void upload(int video) {\n st.erase(video);\n }\n \n int longest() {\n return (*st.begin())-1;\n }\n};\n\n``` | 1 | 0 | [] | 0 |
longest-uploaded-prefix | Easy JS Solution: Queue | easy-js-solution-queue-by-dollysingh-tuzp | Explanation:\nData structure : Queue. \n\n\nvar LUPrefix = function(n) {\n let q = new Array(n).fill(0);\n this.q = q;\n this.f = 0; //"f" is front of | dollysingh | NORMAL | 2022-10-04T18:00:09.101073+00:00 | 2022-10-04T18:00:09.101113+00:00 | 84 | false | **Explanation:**\nData structure : Queue. \n\n```\nvar LUPrefix = function(n) {\n let q = new Array(n).fill(0);\n this.q = q;\n this.f = 0; //"f" is front of queue\n};\n\n//O(1)\nLUPrefix.prototype.upload = function(video) {\n this.q[video - 1] = 1;\n};\n\n//O(n)\nLUPrefix.prototype.longest = function() {\n while(this.q[this.f] && this.f < this.q.length) {\n this.f += 1;\n }\n return this.f;\n};\n ``` | 1 | 0 | ['Queue', 'JavaScript'] | 0 |
longest-uploaded-prefix | ✅ [Rust] fastest (100%) solution using boolean array (with detailed comments) | rust-fastest-100-solution-using-boolean-is2la | This solution employs a simple boolean array to store the upload status that is used to update longest prefix index. It demonstrated 98 ms runtime (100.00%) and | stanislav-iablokov | NORMAL | 2022-10-03T12:16:22.056899+00:00 | 2022-10-23T12:46:40.488448+00:00 | 79 | false | This [**solution**](https://leetcode.com/submissions/detail/814188631/) employs a simple boolean array to store the upload status that is used to update longest prefix index. It demonstrated **98 ms runtime (100.00%)** and used **54.5 MB memory (100.00%)**. Time complexity is linear: **O(N)**. Space complexity is constant: **O(1)**. Detailed comments are provided.\n\n**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n```\nstruct LUPrefix \n{\n prefixes : Vec<bool>,\n longest_prefix : i32\n}\n\nimpl LUPrefix \n{\n fn new(n: i32) -> Self \n {\n LUPrefix{ prefixes: vec![false;n as usize +2], longest_prefix: 0 }\n }\n \n fn upload(&mut self, video: i32) \n {\n self.prefixes[video as usize] = true;\n }\n \n fn longest(&mut self) -> i32\n {\n // on request, update the longest prefix using \n // the upload status data from the boolean array \n while self.prefixes[self.longest_prefix as usize + 1]\n {\n self.longest_prefix += 1;\n }\n\n self.longest_prefix\n }\n}\n```\n | 1 | 0 | ['Array', 'Rust'] | 0 |
longest-uploaded-prefix | C++ solution using Fenwick Tree + Binary Search | c-solution-using-fenwick-tree-binary-sea-u5lf | Solution:\n```\ntemplate\nclass BIT {\npublic:\n vector bit;\n int n;\n \n BIT() {}\n \n BIT(int _n) {\n n = _n;\n bit = vector( | dhavalkumar | NORMAL | 2022-10-03T05:10:37.023618+00:00 | 2022-10-03T05:10:37.023657+00:00 | 157 | false | **Solution:**\n```\ntemplate<typename T>\nclass BIT {\npublic:\n vector<T> bit;\n int n;\n \n BIT() {}\n \n BIT(int _n) {\n n = _n;\n bit = vector<T>(n, 0LL);\n }\n \n void inc(int idx, T val) {\n for(int i = idx + 1; i <= n; i += (i & -i)) \n bit[i - 1] += val;\n }\n \n T at(int idx) {\n T res = 0;\n for(int i = idx + 1; i > 0; i -= (i & -i)) \n res += bit[i - 1];\n return res;\n }\n \n T at(int l, int r) {\n return at(r) - (l - 1 >= 0? at(l - 1): 0);\n }\n \n};\n\nclass LUPrefix {\npublic:\n BIT<int> bit;\n \n LUPrefix(int n) {\n bit = BIT<int>(1e5 + 2); \n }\n \n void upload(int video) {\n bit.inc(video, 1);\n }\n \n int longest() {\n int l = 0, r = 1e5 + 1;\n while(r - l > 1) {\n int m = l + (r - l) / 2;\n if(bit.at(1, m) >= m) l = m;\n else r = m;\n }\n return l;\n }\n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */ | 1 | 0 | ['Binary Indexed Tree', 'Binary Tree'] | 0 |
longest-uploaded-prefix | [Python 3] Only update left and right endpoints | Time O(1), Space O(N) | python-3-only-update-left-and-right-endp-q2lv | If we maintain a list for all the segments so far, the longest uploaded prefix essentially is the size of the first element a.k.a self.P[1] in my case for avoid | zhuzhengyuan824 | NORMAL | 2022-10-02T20:54:45.459935+00:00 | 2022-10-02T20:58:54.059587+00:00 | 165 | false | If we maintain a list for all the segments so far, the longest uploaded prefix essentially is the size of the first element a.k.a `self.P[1]` in my case for avoiding index overflow.\n\nThe only tricky part is the way to update left&right most endpoints: \n1. find left most endpoint(`x-self.P[x-1]`) and rightmost endpoint(`x+self.P[x+1]`)\n2. update the whole segment by summing up two segments and plus more element (`self.P[x-1]+self.P[x+1]+1`)\n\n```\nclass LUPrefix:\n def __init__(self, n: int):\n self.P = [0]*(n+2)\n\n def upload(self, x: int) -> None:\n self.P[x-self.P[x-1]] = self.P[x+self.P[x+1]] = self.P[x-1]+self.P[x+1]+1\n\n def longest(self) -> int:\n return self.P[1]\n``` | 1 | 0 | ['Python'] | 0 |
longest-uploaded-prefix | c++ simple solution | c-simple-solution-by-hanzhoutang-ue1x | The idea is that after one video has been uploaded, it will never be removed, which means the logested prefix keeps growing and we can simply track the by a si | hanzhoutang | NORMAL | 2022-10-02T20:23:27.212958+00:00 | 2022-10-02T20:25:36.980115+00:00 | 35 | false | The idea is that after one video has been uploaded, it will never be removed, which means the logested prefix keeps growing and we can simply track the by a single variable. (The intuition here is very samilar to sliding window)\nAnd since the simple variable will move from 0 to n. We know the time complixity is actually O(n). The solution is good enough and no need for any other fancy data structure. \nCode below \n```\nclass LUPrefix {\npublic:\n vector<int> data; \n int s = 0; \n LUPrefix(int n) {\n data.resize(n);\n }\n \n void upload(int i) {\n data[i-1] = 1; \n }\n \n int longest() {\n while(s<data.size()&&data[s]) {\n s++;\n }\n return s; \n }\n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n ``` | 1 | 0 | [] | 0 |
longest-uploaded-prefix | c#, Sorted Set | c-sorted-set-by-bytchenko-bcn3 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe can store unloaded chunks, so to compupute the prefix we should find the min unloade | bytchenko | NORMAL | 2022-10-02T10:38:04.664043+00:00 | 2022-10-02T10:38:04.664089+00:00 | 29 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can store **unloaded** chunks, so to compupute the prefix we should find the min unloaded chunk.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can use `SortedSet<int>` to store **unloaded** chunks\n\n# Complexity\n- Time complexity:\nO(N * log (N)) to initialize the instance\nO(log(N)) to add\nO(1) to query \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N) \n# Code\n```\npublic class LUPrefix {\n private SortedSet<int> m_Empty;\n\n public LUPrefix(int n) {\n m_Empty = new SortedSet<int>(Enumerable.Range(1, n + 1));\n }\n \n public void Upload(int video) => m_Empty.Remove(video); \n \n public int Longest() => m_Empty.Min - 1;\n}\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix obj = new LUPrefix(n);\n * obj.Upload(video);\n * int param_2 = obj.Longest();\n */\n``` | 1 | 0 | ['C#'] | 0 |
longest-uploaded-prefix | C++ | Vector | Pointer | Well Commented | O(n) solution | c-vector-pointer-well-commented-on-solut-ydhx | Please upvote if you like!!\n\nTC: O(n)\nSC: O(n)\n\nclass LUPrefix {\npublic:\n\t// we will use a vector to keep track of the uploaded videos\n vector<int> | _prit | NORMAL | 2022-10-02T05:32:50.845855+00:00 | 2022-10-02T05:33:13.710056+00:00 | 55 | false | **Please upvote if you like!!**\n\nTC: O(n)\nSC: O(n)\n``` \nclass LUPrefix {\npublic:\n\t// we will use a vector to keep track of the uploaded videos\n vector<int> v;\n int pointer;\n \n LUPrefix(int n) {\n\t\t// initialize the vector of size (n+1) as the video indexes start from 1 to n\n v.resize(n+1, 0);\n\t\t// pointer will keep track of the longest uploaded prefix\n\t\t// eg. at first it will be at v[0] indicating that first video is not uploaded\n pointer = 0;\n }\n \n void upload(int video) {\n\t\t// keep track of which video is uploaded\n v[video]++;\n\t\t\n\t\t// increment the pointer so that it points to the maximum index till which all videos are uploaded\n for(int x=pointer+1; x<v.size(); x++){\n if(v[x] != 0){\n pointer = x;\n } else if(v[x] == 0){\n break;\n }\n }\n }\n \n int longest() {\n\t\t// just return the pointer\n return pointer;\n }\n};\n\n/**\n * Your LUPrefix object will be instantiated and called as such:\n * LUPrefix* obj = new LUPrefix(n);\n * obj->upload(video);\n * int param_2 = obj->longest();\n */\n``` | 1 | 0 | ['C'] | 0 |
longest-uploaded-prefix | C++ || Easy & Simple || Amortized O(1) || 100% faster | c-easy-simple-amortized-o1-100-faster-by-dtl7 | \nclass LUPrefix {\npublic:\n vector<bool>uploaded;\n int size;\n int longestPrefix;\n LUPrefix(int n) {\n size = n;\n uploaded.resize | AJAY_MAKVANA | NORMAL | 2022-10-02T05:09:00.167742+00:00 | 2022-10-02T05:10:33.439512+00:00 | 58 | false | ```\nclass LUPrefix {\npublic:\n vector<bool>uploaded;\n int size;\n int longestPrefix;\n LUPrefix(int n) {\n size = n;\n uploaded.resize(size + 1, false);\n longestPrefix = 0;\n }\n\n void upload(int video) {\n uploaded[video] = true;\n }\n\n int longest() {\n while ((longestPrefix + 1 <= size) && uploaded[longestPrefix + 1]) {\n longestPrefix++;\n }\n return longestPrefix;\n }\n};\n```\n**Time Complexity : O(1)**\n**Space Complexity : O(n)**\n\n\n | 1 | 0 | ['C', 'C++'] | 0 |
longest-uploaded-prefix | C++|| SET|| Easy | c-set-easy-by-aakash_172-2guk | \nclass LUPrefix {\npublic:\n set<int>st;\n LUPrefix(int n) {\n for(int i=1;i<=n+1;i++){\n st.insert(i);\n }\n }\n \n vo | aakash_172 | NORMAL | 2022-10-01T21:36:37.768224+00:00 | 2022-10-01T21:36:37.768263+00:00 | 38 | false | ```\nclass LUPrefix {\npublic:\n set<int>st;\n LUPrefix(int n) {\n for(int i=1;i<=n+1;i++){\n st.insert(i);\n }\n }\n \n void upload(int video) {\n st.erase(video);\n }\n \n int longest() {\n return (*st.begin())-1;\n }\n};\n``` | 1 | 0 | ['C', 'Ordered Set'] | 0 |
longest-uploaded-prefix | Easy and optimized python3 solution | easy-and-optimized-python3-solution-by-m-4mi8 | class LUPrefix:\n\n def init(self, n: int):\n \n self.v = [0]*(n+1)\n self.cur = 1\n \n\n def upload(self, video: int) -> None | mayankmaheshwari | NORMAL | 2022-10-01T20:21:41.712865+00:00 | 2022-10-01T20:23:44.703539+00:00 | 123 | false | class LUPrefix:\n\n def __init__(self, n: int):\n \n self.v = [0]*(n+1)\n self.cur = 1\n \n\n def upload(self, video: int) -> None:\n self.v[video] = 1\n if video == self.cur:\n self.cur+=1\n \n while self.cur<len(self.v) and self.v[self.cur]!=0:\n self.cur+=1\n\n\n def longest(self) -> int:\n return self.cur-1 | 1 | 0 | ['Python3'] | 0 |
longest-uploaded-prefix | Python All O(1) endpoint algorithm, no amortization | python-all-o1-endpoint-algorithm-no-amor-3hod | It\'s quite straightforward to get amortized O(logn) with SortedList or amortized O(1) by counting up till the missing video. However, if you are familiar with | chuan-chih | NORMAL | 2022-10-01T19:59:08.486019+00:00 | 2022-10-01T20:22:44.692065+00:00 | 167 | false | It\'s quite straightforward to get amortized `O(logn)` with `SortedList` or amortized `O(1)` by counting up till the missing `video`. However, if you are familiar with the "endpoint algorithm" that keeps track of all the contiguous segments, it\'s just as simple to get an all `O(1)` algorithm:\n\n1. Use `left` and `right` dictionaries to map the right endpoint to the left endpoint of the segment, and vice versa.\n2. Given a new `video`, check if `video - 1` is in `left`. If it is, `left[video - 1]` will be the new left endpoint instead.\n3. Likewise, if `video + 1` is in `right`, `right[video + 1]` will be the new right endpoint instead.\n4. Finally, return `right[1]` if `1` is in `right`, else `0` for `longest()`.\n\n```\nclass LUPrefix:\n\n def __init__(self, n: int):\n self.left = {}\n self.right = {}\n\n def upload(self, video: int) -> None:\n l = self.left.pop(video - 1, video)\n r = self.right.pop(video + 1, video)\n self.left[r] = l\n self.right[l] = r\n\n def longest(self) -> int:\n return self.right.get(1, 0)\n``` | 1 | 0 | ['Python'] | 1 |
longest-uploaded-prefix | Python Easy Solution | python-easy-solution-by-titanolodon-xkq4 | \nclass LUPrefix:\n\n def __init__(self, n: int) -> None:\n \n self.uploaded = set()\n self.prefix = list(range(n, -1, -1))\n \n | Titanolodon | NORMAL | 2022-10-01T19:31:25.046012+00:00 | 2022-10-01T19:31:25.046051+00:00 | 78 | false | ```\nclass LUPrefix:\n\n def __init__(self, n: int) -> None:\n \n self.uploaded = set()\n self.prefix = list(range(n, -1, -1))\n \n def upload(self, video: int) -> None:\n \n self.uploaded.add(video - 1)\n\t\t\n while self.prefix[-1] in self.uploaded:\n self.prefix.pop()\n \n def longest(self) -> int:\n \n return self.prefix[-1]\n``` | 1 | 0 | ['Python'] | 0 |
longest-uploaded-prefix | Java Array Solution | java-array-solution-by-solved-yrk6 | \nclass LUPrefix {\n boolean[] array;\n int maxSize;\n public LUPrefix(int n) {\n this.array = new boolean[n];\n this.maxSize = 0;\n } | solved | NORMAL | 2022-10-01T19:13:03.012999+00:00 | 2022-10-01T19:13:03.013043+00:00 | 61 | false | ```\nclass LUPrefix {\n boolean[] array;\n int maxSize;\n public LUPrefix(int n) {\n this.array = new boolean[n];\n this.maxSize = 0;\n }\n public void upload(int video) {\n array[video - 1] = true;\n int count = 0;\n for (int i = 0; i < array.length; i++) {\n if (array[i] == true) {\n count++;\n } else {\n maxSize = Math.max(maxSize, count);\n break;\n }\n }\n maxSize = Math.max(maxSize, count);\n }\n public int longest() {\n return maxSize;\n }\n}\n``` | 1 | 0 | ['Array', 'Java'] | 0 |
longest-uploaded-prefix | O(nlogn) using merging lower upper bound intervals | onlogn-using-merging-lower-upper-bound-i-oh59 | Main Idea:\n+ Managing lower/upper bound intervals\n+ Uploading method:\n + vmin, vmax = video, video\n + Find upper bound interval: video - 1 -> found: vmin | dntai | NORMAL | 2022-10-01T18:13:23.528707+00:00 | 2022-10-01T18:13:23.528750+00:00 | 121 | false | **Main Idea**:\n+ Managing lower/upper bound intervals\n+ Uploading method:\n + vmin, vmax = video, video\n + Find upper bound interval: video - 1 -> found: vmin = min(interval), delete lower/upper bound intervals corresponding\n + Find lower bound interval: video + 1 -> found: vmax = max(interval), delete lower/upper bound intervals corresponding\n + Updating lower/upper bound intervals\n+ Longest method: max(upper bound(1) \n\n**Examples**:\n```\n+ Current Status:\nlower bound intervals = {1: [1,3], 5: [5,8]}\nupper bound intervals: {3:[1,3], 8:[5,8]}\n\n+ Upload(4):\nvideo 4 -> vmin=4, vmax = 4\n\nvideo-1 = 3 => found upper bound 3: [1,3]\n-> vmin = 1, upper: {8:[5,8]}, lower: {5: [5,8]}\n\nvideo+1 = 5 => found lower bound 5: [5,8]\n-> vmax = 8, upper: {}, lower: {}\n\nUpdating: lower: {1: [1,8]}, upper: {8: [1,8]}\n\n+ Longest: lower[1][1] -> 8\n```\n\n**Code**:\n```python\nclass LUPrefix:\n def __init__(self, n: int):\n self.check = [0] * (n+1)\n self.n = n\n self.hmin = {}\n self.hmax = {}\n\n def upload(self, video: int) -> None:\n if video>=1 and video<=self.n and self.check[video]==0:\n q1 = self.hmax.get(video-1)\n q2 = self.hmin.get(video+1)\n vmin, vmax = [video, video]\n if q1 is not None and q2 is not None:\n vmin, vmax = q1[0], q2[1]\n del self.hmax[video-1]\n del self.hmin[video+1]\n elif q1 is not None:\n vmin, vmax = q1[0], video\n del self.hmax[q1[1]]\n elif q2 is not None:\n vmin, vmax = video, q2[1]\n del self.hmin[q2[0]]\n self.hmax[vmax] = [vmin, vmax]\n self.hmin[vmin] = [vmin, vmax] \n self.check[video] = 1\n \n # print(q1, q2, self.check, self.hmin, self.hmax)\n \n def longest(self) -> int:\n if self.hmin.get(1) is None:\n return 0\n else:\n return self.hmin[1][1]\n\n\n# Your LUPrefix object will be instantiated and called as such:\n# obj = LUPrefix(n)\n# obj.upload(video)\n# param_2 = obj.longest()\n``` | 1 | 0 | ['Python3'] | 0 |
longest-uploaded-prefix | Simple swift solution | simple-swift-solution-by-zhedre1n-565v | \nclass LUPrefix {\n var last = 0\n var cache = Set<Int>()\n\n init(_ n: Int) {}\n \n func upload(_ video: Int) {\n appendIfNeeded(video)\ | ZheDre1N | NORMAL | 2022-10-01T18:09:17.364618+00:00 | 2022-10-01T18:25:32.436772+00:00 | 50 | false | ```\nclass LUPrefix {\n var last = 0\n var cache = Set<Int>()\n\n init(_ n: Int) {}\n \n func upload(_ video: Int) {\n appendIfNeeded(video)\n }\n \n func longest() -> Int {\n last\n }\n \n private func appendIfNeeded(_ video: Int) {\n if last + 1 == video {\n self.last = video\n processCacheIfNeeded()\n } else {\n cache.insert(video)\n }\n }\n \n private func processCacheIfNeeded() {\n guard !cache.isEmpty else { return }\n while cache.contains(last + 1) {\n last += 1\n }\n }\n}\n```\n | 1 | 0 | ['Swift'] | 0 |
longest-uploaded-prefix | Two very efficient Solutions | Python | two-very-efficient-solutions-python-by-s-v321 | Sorted List solution:\n\nfrom sortedcontainers import SortedList\n\nclass LUPrefix:\n def __init__(self, n: int):\n self.notUploaded = SortedList(i fo | swissnerd | NORMAL | 2022-10-01T17:55:12.521228+00:00 | 2022-10-01T18:51:18.230826+00:00 | 71 | false | **Sorted List** solution:\n```\nfrom sortedcontainers import SortedList\n\nclass LUPrefix:\n def __init__(self, n: int):\n self.notUploaded = SortedList(i for i in range(n + 1))\n # Time: O(n)\n # Space: O(n)\n\n def upload(self, video: int) -> None:\n self.notUploaded.remove(video - 1)\n # Time: O(log(n))\n # Space: O(1)\n\n def longest(self) -> int:\n return self.notUploaded[0]\n # Time: O(1)\n # Space: O(1)\n```\n\\\nAlternative solution:\n```\nclass LUPrefix:\n def __init__(self, n: int):\n self.ds = [False] * n\n self.mx = 0\n # Time: O(n)\n # Space: O(n)\n\n def upload(self, video: int) -> None:\n self.ds[video - 1] = True\n while self.mx < len(self.ds) and self.ds[self.mx]:\n self.mx += 1\n # Time: O(m) where m is video\n # Space: O(1)\n\n def longest(self) -> int:\n return self.mx\n # Time: O(1)\n # Space: O(1)\n``` | 1 | 0 | ['Python'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.