Skip to content

Commit

Permalink
Added power of subarrays solution.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Nov 16, 2024
1 parent 129a632 commit e3fa141
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,7 @@ programming challenges completed in other languages.
- Minimized Maximum of Products Distributed to Any Store (https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store)
- Remove K Digits (https://leetcode.com/problems/remove-k-digits)
- Range Frequency Queries (https://leetcode.com/problems/range-frequency-queries)
- Find the Power of K Size Sub-Arrays (https://leetcode.com/problems/find-the-power-of-k-size-subarrays-i)

#### Hard

Expand Down
1 change: 1 addition & 0 deletions src/leetcode/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,4 @@ mod square_numbers;
mod minimized_maximum;
mod remove_k_digits;
mod range_freq;
mod power_of_subarrays;
40 changes: 40 additions & 0 deletions src/leetcode/power_of_subarrays.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
pub fn results_array(numbers: Vec<i32>, k: i32) -> Vec<i32> {
numbers
.windows(k as usize)
.map(|w| {
let (mut prev, mut max) = (w[0], w[0]);
for &val in w.iter().skip(1) {
if prev + 1 != val {
return -1;
}
max = max.max(val);
prev = val;
}
max
})
.collect()
}

#[cfg(test)]
mod tests {
use super::results_array;

#[test]
fn non_consecutive_values() {
assert_eq!(vec![-1, -1], results_array(vec![2, 2, 2, 2, 2], 4))
}

#[test]
fn zipped_consecutive_values() {
assert_eq!(
vec![-1, 3, -1, 3, -1],
results_array(vec![3, 2, 3, 2, 3, 2], 2)
)
}

#[test]
fn k_equals_n() {
assert_eq!(vec![3], results_array(vec![2, 3], 2));
assert_eq!(vec![-1], results_array(vec![3, 2], 2))
}
}

0 comments on commit e3fa141

Please sign in to comment.