LeetCode Entry

3110. Score of a String

01.06.2024 easy 2024 kotlin rust

Sum(abs(window))

3110. Score of a String easy blog post substack youtube 2024-06-01_08-37.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/625

Problem TLDR

Sum(abs(window)) #easy

Intuition

Just do what is asked. Use iterators preferably.

Approach

Some notes to Rust:

  • as_bytes gives a slice of [u8] and slices have a window
  • there is an abs_diff, can save some symbols

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


    fun scoreOfString(s: String): Int =
        s.windowed(2).sumBy { abs(it[0] - it[1]) }


    pub fn score_of_string(s: String) -> i32 {
        s.as_bytes().windows(2)
        .map(|x| x[0].abs_diff(x[1]) as i32).sum()
    }