|
| 1 | +// 2501. Longest Square Streak in an Array |
| 2 | +// 🟠 Medium |
| 3 | +// |
| 4 | +// https://leetcode.com/problems/longest-square-streak-in-an-array/ |
| 5 | +// |
| 6 | +// Tags: Array - Hash Table - Binary Search - Dynamic Programming - Sorting |
| 7 | + |
| 8 | +use std::collections::HashMap; |
| 9 | + |
| 10 | +struct Solution; |
| 11 | +impl Solution { |
| 12 | + /// One way to do it is to sort the input vector, then visit each number, check if we can |
| 13 | + /// append it to any of the existing sequences and either extend that sequence or create a new |
| 14 | + /// one. We determine if we can append to existing sequences using a hashmap with the next |
| 15 | + /// square that would go into the sequence as the key and the length that the sequence would |
| 16 | + /// have, once we append that next sequence, as the value. |
| 17 | + /// |
| 18 | + /// Time complexity: O(nlog(n)) - We sort the input vector, after that O(n) |
| 19 | + /// Space complexity: O(n) - The hashmap grows to size n. |
| 20 | + /// |
| 21 | + /// Runtime 28 ms Beats 100% |
| 22 | + /// Memory 5.17 MB Beats 100% |
| 23 | + pub fn longest_square_streak(mut nums: Vec<i32>) -> i32 { |
| 24 | + nums.sort_unstable(); |
| 25 | + // A hashmap of the next squares with the sequence length. |
| 26 | + let mut next_squares = HashMap::new(); |
| 27 | + let mut res = -1; |
| 28 | + for num in nums { |
| 29 | + // Skip duplicates. |
| 30 | + if next_squares.contains_key(&(num * num)) { |
| 31 | + continue; |
| 32 | + } |
| 33 | + // Can I append to an existing sequence? |
| 34 | + if let Some(&counter) = next_squares.get(&num) { |
| 35 | + res = res.max(counter); |
| 36 | + next_squares.insert(num * num, counter + 1); |
| 37 | + } else { |
| 38 | + next_squares.insert(num * num, 2); |
| 39 | + } |
| 40 | + } |
| 41 | + res |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// Tests. |
| 46 | +fn main() { |
| 47 | + let tests = [(vec![4, 3, 6, 16, 8, 2], 3), (vec![2, 3, 5, 6, 7], -1)]; |
| 48 | + println!("\n\x1b[92m» Running {} tests...\x1b[0m", tests.len()); |
| 49 | + let mut success = 0; |
| 50 | + for (i, t) in tests.iter().enumerate() { |
| 51 | + let res = Solution::longest_square_streak(t.0.clone()); |
| 52 | + if res == t.1 { |
| 53 | + success += 1; |
| 54 | + println!("\x1b[92m✔\x1b[95m Test {} passed!\x1b[0m", i); |
| 55 | + } else { |
| 56 | + println!( |
| 57 | + "\x1b[31mx\x1b[95m Test {} failed expected: {:?} but got {}!!\x1b[0m", |
| 58 | + i, t.1, res |
| 59 | + ); |
| 60 | + } |
| 61 | + } |
| 62 | + println!(); |
| 63 | + if success == tests.len() { |
| 64 | + println!("\x1b[30;42m✔ All tests passed!\x1b[0m") |
| 65 | + } else if success == 0 { |
| 66 | + println!("\x1b[31mx \x1b[41;37mAll tests failed!\x1b[0m") |
| 67 | + } else { |
| 68 | + println!( |
| 69 | + "\x1b[31mx\x1b[95m {} tests failed!\x1b[0m", |
| 70 | + tests.len() - success |
| 71 | + ) |
| 72 | + } |
| 73 | +} |
0 commit comments