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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
flatten-a-multilevel-doubly-linked-list | JAVA 1ms DFS Self Explainatory Easy | java-1ms-dfs-self-explainatory-easy-by-b-ykvg | \nclass Solution {\n public Node flatten(Node head) {\n if(head == null) return null;\n Node ptr = head;\n while(ptr.next != null) ptr = | bharat194 | NORMAL | 2022-03-16T08:53:26.696739+00:00 | 2022-03-16T08:54:31.040276+00:00 | 129 | false | ```\nclass Solution {\n public Node flatten(Node head) {\n if(head == null) return null;\n Node ptr = head;\n while(ptr.next != null) ptr = ptr.next;\n Node p = head;\n while(p != null){\n if(p.child != null){\n Node chi = p.child;\n Node nxt = p.next;\n p.child = null;\n flatten(chi);\n Node end = chi;\n while(end.next != null) end = end.next;\n p.next = chi;\n chi.prev = p;\n end.next = nxt;\n if(nxt != null)nxt.prev = end;\n }\n p=p.next;\n }\n return head;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
flatten-a-multilevel-doubly-linked-list | Python solution, Easy Understanding without using stack | python-solution-easy-understanding-witho-g4e9 | \nclass Solution:\n def flatten(self, head: \'Optional[Node]\') -> \'Optional[Node]\':\n if head is None:\n return\n c = head\n | Nish786 | NORMAL | 2022-02-08T06:58:19.596067+00:00 | 2022-02-11T05:41:24.542104+00:00 | 163 | false | ```\nclass Solution:\n def flatten(self, head: \'Optional[Node]\') -> \'Optional[Node]\':\n if head is None:\n return\n c = head\n while c:\n if c.child is not None:\n ch = c.child\n ch.prev = c\n t = c.next\n c.next = c.child\n c.child = None\n if t is not None:\n while ch.next:\n ch = ch.next\n t.prev = ch \n ch.next = t\n c = c.next\n return head\n```\n\nIf you like this solution upvote | 3 | 0 | ['Linked List', 'Python'] | 0 |
score-of-a-string | One line Solution 😱😱 | one-line-solution-by-hi-malik-h75m | It\'s a pretty simple problem! You just take a character and subtract the next character. If we convert them into integers, they get converted into their ASCII | hi-malik | NORMAL | 2024-06-01T00:23:57.018068+00:00 | 2024-06-01T00:38:39.764572+00:00 | 19,311 | false | It\'s a pretty simple problem! You just take a character and subtract the next character. If we convert them into integers, they get converted into their ASCII values. So, if we subtract two characters, they are actually subtracted based on their ASCII values!\n\nTherefore, it\'s quite simple: you just subtract two adjacent characters and take the absolute difference. Then, you add up all these absolute differences for each pair of adjacent characters. As shown in the diagram, it\'s nothing too complicated.\n\n\n\nLet me explain you the code first :\n\n1. **Initialization**: The variable `total` is initialized to 0.\n2. **Loop**: The `for` loop runs from the first character (`i = 0`) to the second last character (`i < s.length() - 1`).\n3. **Calculation**: Inside the loop, `Math.abs(s.charAt(i) - s.charAt(i + 1))` calculates the absolute difference between the ASCII values of the current character (`s.charAt(i)`) and the next character (`s.charAt(i + 1)`). This value is added to `total`.\n4. **Return**: The function returns the total score after the loop finishes.\n\n**Let\\s code it UP**\n\n### C++ Code\n```cpp\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int total = 0;\n for(int i = 0; i < s.size() - 1; i++) {\n total += abs(s[i] - s[i + 1]);\n }\n return total;\n }\n};\n```\n\n### Java Code\n```java\nclass Solution {\n public int scoreOfString(String s) {\n int total = 0;\n for(int i = 0; i < s.length() - 1; i++) {\n total += Math.abs(s.charAt(i) - s.charAt(i + 1));\n }\n return total;\n }\n}\n```\n\n### Python Code\n```python\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n total = 0\n for i in range(len(s) - 1):\n total += abs(ord(s[i]) - ord(s[i + 1]))\n return total\n```\n\n___\nComplexity Analysis \n___\n\n* **Time Complexity :-** BigO(n)\n* **Space Complexity :-** BigO(1)\n\n___\n___\n\n**One Line Solution**\n\n\n**C++**\n\n```cpp\nclass Solution {\npublic:\n int scoreOfString(string s) {\n return accumulate(next(s.begin()), s.end(), 0, [&s](int total, char c, size_t i = 0) mutable {\n return total + abs(s[i++] - c);\n });\n }\n};\n```\n\n**JAVA**\n\n```java\npublic class Solution {\n public int scoreOfString(String s) {\n return java.util.stream.IntStream.range(0, s.length() - 1).map(i -> Math.abs(s.charAt(i) - s.charAt(i + 1))).sum();\n }\n}\n```\n\n**PYTHON**\n\n```python\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n return sum(abs(ord(s[i]) - ord(s[i + 1])) for i in range(len(s) - 1))\n```\n | 44 | 3 | ['C', 'Python', 'Java'] | 15 |
score-of-a-string | 💯Faster✅💯Less Mem✅Detailed Explaination🎯Linear Iter🧠Step-by-Step Explaination✅Python🐍Java🍵 | fasterless-memdetailed-explainationlinea-2p98 | \uD83D\uDE80 Hi, I\'m Mohammed Raziullah Ansari, and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explain | Mohammed_Raziullah_Ansari | NORMAL | 2024-06-01T02:38:06.639960+00:00 | 2024-06-01T02:51:32.656030+00:00 | 6,591 | false | # \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share solution to this question with detailed explanation:\n\n# \uD83C\uDFAFProblem Explaination: \nThe problem is to compute the score of a given string `s`. The score is calculated based on the absolute differences between the ASCII values of each pair of adjacent characters in the string. Here\'s a explanation to it:\n\n1. **Understanding ASCII Values**: Each character in the string has an ASCII value, which is a numerical representation of the character. For example, the ASCII value of \'a\' is 97, and the ASCII value of \'b\' is 98.\n\n2. **Adjacent Characters**: Two characters are adjacent if they are next to each other in the string. For example, in the string "abc", the pairs of adjacent characters are (\'a\', \'b\') and (\'b\', \'c\').\n\n3. **Absolute Difference**: The absolute difference between two numbers is the non-negative difference between them. For example, the absolute difference between the ASCII values of \'a\' (97) and \'b\' (98) is |97 - 98| = 1.\n\n4. **Score Calculation**: To calculate the score of the string, sum the absolute differences between the ASCII values of all adjacent character pairs in the string.\n\n## \uD83D\uDCE5Input\n- A single string `s` which can contain any printable ASCII characters.\n\n## \uD83D\uDCE4Output\n- An integer representing the score of the string `s`.\n\n# \u2705Approach:\n- **Initialization**: Start with `score = 0`.\n- **Loop Through the String**: Use a loop that runs from the first to the second last character.\n- **Calculate and Update**: In each iteration of the loop, calculate the absolute difference between the current character and the next character, and add this difference to `score`.\n- **Return the Score**: After the loop, return the accumulated `score`.\n\n# Let\'s walkthrough\uD83D\uDEB6\uD83C\uDFFB\u200D\u2642\uFE0F the implementation process with an example for better understanding\uD83C\uDFAF:\n\nLet\'s walk through the code step by step with the input `s = "abcd"`.\n\n1. **ASCII Values**: \n - \'a\' = 97\n - \'b\' = 98\n - \'c\' = 99\n - \'d\' = 100\n\n2. **Adjacent Pairs and Differences**:\n - (\'a\', \'b\'): |97 - 98| = 1\n - (\'b\', \'c\'): |98 - 99| = 1\n - (\'c\', \'d\'): |99 - 100| = 1\n\n3. **Sum of Differences**:\n - 1 (from \'a\' and \'b\') + 1 (from \'b\' and \'c\') + 1 (from \'c\' and \'d\') = 3\n\n4. **Final Score**:\n - The final score for the string "abcd" is 3.\n\n\n# Code:\n```Python []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n score = 0\n for i in range(len(s) - 1):\n score += abs(ord(s[i]) - ord(s[i + 1]))\n return score \n```\n```Java []\npublic class Solution {\n public int scoreOfString(String s) {\n int score = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n score += Math.abs(s.charAt(i) - s.charAt(i + 1));\n }\n return score;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int score = 0;\n for (size_t i = 0; i < s.length() - 1; i++) {\n score += abs(s[i] - s[i + 1]);\n }\n return score;\n }\n};\n\n```\n# \uD83D\uDCA1 I invite you to check out [my profile](https://leetcode.com/Mohammed_Raziullah_Ansari/) for detailed explanations and code for each method. Happy coding and learning! \uD83D\uDCDA | 32 | 1 | ['String', 'C++', 'Java', 'Python3'] | 5 |
score-of-a-string | Easy string vs adjacent_difference+accumulate vs 1-line recursion||0ms beats 100% | easy-string-vs-adjacent_differenceaccumu-epwl | Intuition\n Describe your first thoughts on how to solve this problem. \nVery easy question!\n\nFor exercise, use C++ STL to make the 2nd approach; adjacent_dif | anwendeng | NORMAL | 2024-06-01T00:04:34.381879+00:00 | 2024-06-01T09:34:02.000430+00:00 | 7,553 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nVery easy question!\n\nFor exercise, use C++ STL to make the 2nd approach; adjacent_difference, accumulate with lambda function\n\n3rd approach is 1-line recursion.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse a loop to iterate\n```\nfor(int i=1; i<n; i++)\n ans+=abs(s[i]-s[i-1]);\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)\\to O(n)$$\n# Code||Python 1-liner| C, C++ 0ms beats 100%\n```C []\n#pragma GCC optimize("O3", "unroll-loops")\nstatic int scoreOfString(char* s) {\n int ans=0;\n for(register int i=1; s[i]!=\'\\0\'; i++)\n ans+=abs(s[i]-s[i-1]);\n return ans;\n}\n```\n```Python []\nclass Solution(object):\n def scoreOfString(self, s):\n return sum(abs(ord(s[i])-ord(s[i-1])) for i in range(1, len(s)))\n```\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(string& s) {\n int n=s.size();\n int ans=0;\n for(int i=1; i<n; i++)\n ans+=abs(s[i]-s[i-1]);\n return ans; \n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n```\n\n# C++ using adjacent_difference+accumulate||0ms beats 100%\nFor testcase `s="hello"`, one has\n```\n[104,101,108,108,111] for s\n[104,-3,7,0,3] for s after adjacent_difference\n=> ans=|-3|+7+0+3=13\n```\n# C++ code\n```\nclass Solution {\npublic:\n static int scoreOfString(string& s) {\n adjacent_difference(s.begin(), s.end(), s.begin());\n \n //sum the absolute values of the differences, starting from the second element\n return accumulate(s.begin()+1, s.end(), 0, [](int x, int y){\n return x+abs(y);\n });\n }\n};\n\n```\n# Code 1-line recursion||C++ 0ms beats 100%\nFor 1-liner, add an extra parameter `int i=1`\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(string& s, int i=1) {\n return (i==s.size())?0:abs(s[i]-s[i-1])+scoreOfString(s, i+1);\n }\n};\n```\n```Python []\nclass Solution:\n def scoreOfString(self, s: str, i: int=1) -> int:\n return abs(ord(s[i])-ord(s[i-1]))+self.scoreOfString(s, i+1) if i!=len(s) else 0\n \n``` | 31 | 0 | ['String', 'Recursion', 'C', 'Python', 'C++'] | 9 |
score-of-a-string | ⬆️🔥 Beats 100% | Space O(1) | Time O(n) | Python3 | Easy ✅ | beats-100-space-o1-time-on-python3-easy-gm3ud | Submission\n\n\n\n# Intuition\n\nThe question is to calculate the sum of the absolute difference between every two consecutive elements\' ASCII value, so you ne | adityasony967 | NORMAL | 2024-04-15T18:11:13.847332+00:00 | 2024-04-15T18:11:13.847356+00:00 | 2,297 | false | # Submission\n\n\n\n# Intuition\n\nThe question is to calculate the sum of the absolute difference between every two consecutive elements\' `ASCII` value, so you need to iterate through strings using the `for` (or) `while` loop.\n\nTo calculate the absolute difference between two numbers in Python, you can use the abs() function. Here\'s how you can do it:\n\n```\nabsolute_difference = abs(num1 - num2)\n```\n\nIn Python, the ord() function is used to retrieve the ASCII value (Unicode code point) of a single character. It takes a single character (a string of length 1) as an argument and returns an integer representing its Unicode code point.\n```\nchar = \'A\'\nascii_value = ord(char)\n```\n\n##### Note: \nIn Python, the abs() function is a built-in function used to return the absolute value of a number. The absolute value of a number is its distance from zero on the number line, regardless of its sign. \n\n\n# Approach\n1. First, initialize and assign the initial value of the score variable to zero.\n\n2. Run the loop until `length -1 times`, so from index zero to index length of s - 2 , which is :\n\n```\nfor i in range(len(s)-1)\n```\n3. Each time you iterate, update the score value by the absolute difference between the `s[i] and s[i+1]` elements\' ASCII values in string s.\n```\nscore += abs(ord(s[i]) - ord(s[i+1]))\n```\n4. Now, finally, `return` the score outside the loop.\n\n# Complexity\n\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n\n score = 0\n for i in range(len(s)-1):\n score += abs(ord(s[i]) - ord(s[i+1]))\n \n return score\n \n``` | 21 | 1 | ['String', 'Python3'] | 2 |
score-of-a-string | ✅ EASY WITH EXPLANATION || 💯 % on runtime 🚀 | easy-with-explanation-on-runtime-by-iamh-mo8t | Intuition \uD83C\uDF1F\n\nWhen given a string, one natural way to measure how "different" consecutive characters are is to look at their ASCII values. By calcul | IamHazra | NORMAL | 2024-06-01T06:16:54.219642+00:00 | 2024-06-01T15:01:43.955251+00:00 | 3,321 | false | # Intuition \uD83C\uDF1F\n\nWhen given a string, one natural way to measure how "different" consecutive characters are is to look at their ASCII values. By calculating the absolute difference between the ASCII values of consecutive characters in the string, we can get a measure of how "different" the string is at each step. Summing these differences will give us the total score of the string.\n\n# Approach \uD83D\uDE80\n\nTo solve this problem, we can break down the solution into the following steps:\n\n1. **Initialize Variables**: Start by initializing a variable `ans` to store the cumulative score.\n2. **Iterate Through the String**: Loop through the string starting from the second character (index 1) to the end.\n3. **Calculate ASCII Differences**: For each character in the string (from the second character onwards), calculate the absolute difference between its ASCII value and the ASCII value of the previous character.\n4. **Accumulate the Differences**: Add each calculated absolute difference to the variable `ans`.\n5. **Return the Result**: After the loop finishes, `ans` will contain the total score of the string, which we then return.\n\nThis approach ensures that we consider the differences between all consecutive characters in the string, and by using the absolute value, we handle both positive and negative differences uniformly.\n\n# Complexity Analysis \uD83D\uDCCA\n\n- **Time Complexity**: The time complexity of this approach is **O(n)**, where **n** is the length of the string. This is because we have to iterate through the entire string once to calculate the differences.\n- **Space Complexity**: The space complexity is **O(1)** as we are using a constant amount of extra space regardless of the input string size.\n\n# Code \uD83D\uDDA5\uFE0F\n\n### Java \u2615\n```java\nclass Solution {\n public int scoreOfString(String s) {\n int ans = 0;\n for(int i=1;i<s.length();i++){\n ans += Math.abs(s.charAt(i-1)-s.charAt(i));\n }\n return ans;\n }\n}\n```\n\n### JavaScript \uD83C\uDF10\n```javascript\n/**\n * @param {string} s\n * @return {number}\n */\nvar scoreOfString = (s) => {\n let ans = 0;\n for (let i = 1; i < s.length; i++) {\n ans += Math.abs(s.charCodeAt(i - 1) - s.charCodeAt(i));\n }\n return ans;\n};\n```\n\n### Python \uD83D\uDC0D\n```python\nclass Solution(object):\n def scoreOfString(self, s):\n """\n :type s: str\n :rtype: int\n """\n ans = 0\n for i in range(1, len(s), 1):\n ans += abs(ord(s[i - 1]) - ord(s[i]))\n return ans\n```\n\n### Python (Python 3) \uD83D\uDC0D\n```python\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n ans = 0\n for i in range(1, len(s), 1):\n ans += abs(ord(s[i - 1]) - ord(s[i]))\n return ans\n```\n\n### C++ \uD83D\uDCBB\n```cpp\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int ans = 0;\n for (int i = 1; i < s.size(); i++) {\n ans += abs(s[i - 1] - s[i]);\n }\n return ans;\n }\n};\n``` | 13 | 0 | ['String', 'Python', 'C++', 'Java', 'Python3', 'JavaScript'] | 5 |
score-of-a-string | ✅Detailed Explanation💯Beginner Friendly🔥Simple and Easy🔥Strings🔥 | detailed-explanationbeginner-friendlysup-xbqv | Submission Link: Python-96.79%,Java-99.87%,C++ - 100%🎯 Problem ExplanationWe are given a stringsand we need to calculate the score of this string.The score is | Saketh3011 | NORMAL | 2024-06-01T00:32:52.912031+00:00 | 2025-02-22T14:21:54.158228+00:00 | 1,524 | false | 

**Submission Link:** [Python-96.79%](https://leetcode.com/problems/score-of-a-string/submissions/1273707818?envType=daily-question&envId=2024-06-01), [Java-99.87%](https://leetcode.com/problems/score-of-a-string/submissions/1273713616?envType=daily-question&envId=2024-06-01), [C++ - 100%](https://leetcode.com/problems/score-of-a-string/submissions/1273715136?envType=daily-question&envId=2024-06-01)
# 🎯 Problem Explanation
We are given a string `s` and we need to calculate the score of this string.
The score is defined as the sum of the absolute differences between the ASCII values of each pair of adjacent/side-by-side characters in the string. Essentially, for each pair of characters next to each other, we find the difference in their ASCII values, take the absolute value of that difference, and sum all these values to get the final score.
# 🤔 Intuition:
The intuition is straightforward: iterate through the string from index 0 to n-2(last 2nd character) and compute the absolute difference between each consecutive pair of characters.
### What do you need to know before?
- Absolute difference is modules/positive difference between two numbers.
- We perform this |a-b| with `abs()` or `Math.abs()` method according to language.
- ASCII values are the numerical representations of characters in the ASCII (American Standard Code for Information Interchange) encoding system, where each character is assigned a unique integer between **0** and **127**.
- Lower case alphabets starts from `97`(a) to `122`(z).
- In some languages like Java & C++ we can directly subtract string, internally ASCII values are subtracted.
- For other languages which doesn't support operation between character, first we have to get ASCII values then subtract. We can use `ord()` method to get character's ASCII value.
> We can use `chr()` function to do the reverse. ASCII value to character.
# ⚙️ Dry Run:
Input: s = "hello"
Initialize: res = 0
|Iteration|s[i]|s[i+1]|┃s[i] - s[i+1]┃|res|
|:-:|:------:|:------:|:--:|:----:|
| 0 | h->104 | e->101 | 3 | 3 (+3) |
| 1 | e->101 | l->108 | -7 | 10 (+7) |
| 2 | l->108 | l->108 | 0 | 10 (+0) |
| 3 | l->108 | o->111 | -3 | 13 (+3) |
# 🧠 Approach:
1. **Initialize a Variable for the Score**:
- Start with a variable `res` initialized to 0 to keep track of the total score.
2. **Iterate Through the String**:
- Use a loop to go through each character in the string except the last one.
- For each character, calculate the absolute difference between its ASCII value and the ASCII value of the next character.
- Add this difference to `res`.
3. **Return the Result**:
- After processing all the characters, return the total score stored in `res`.
# 📒 Complexity:
- ⏰ Time complexity: $$O(n)$$. We iterate through the string once, so the time complexity is linear.
- 🧺 Space complexity: $$O(1)$$. We only use a few extra variables for the computation, so the space complexity is constant.
# 🧑💻 Code
``` python []
class Solution:
def scoreOfString(self, s: str) -> int:
res = 0
for i in range(len(s) - 1):
res += abs(ord(s[i]) - ord(s[i+1]))
return res
```
``` java []
class Solution {
public int scoreOfString(String s) {
int res = 0;
for (int i = 0; i < s.length() - 1; i++) {
res += Math.abs(s.charAt(i) - s.charAt(i + 1));
}
return res;
}
}
```
``` cpp []
class Solution {
public:
int scoreOfString(string s) {
int res = 0;
for (int i = 0; i < s.length() - 1; i++) {
res += abs(s[i] - s[i + 1]);
}
return res;
}
};
```
``` javascript []
var scoreOfString = function(s) {
let res = 0;
for (let i = 0; i < s.length - 1; i++) {
res += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1));
}
return res;
};
```
``` csharp []
public class Solution {
public int ScoreOfString(string s) {
int res = 0;
for (int i = 0; i < s.Length - 1; i++) {
res += Math.Abs(s[i] - s[i + 1]);
}
return res;
}
}
```
``` kotlin []
class Solution {
fun scoreOfString(s: String): Int {
var res = 0
for (i in 0 until s.length - 1) {
res += Math.abs(s[i] - s[i + 1])
}
return res
}
}
```
``` rust []
impl Solution {
pub fn score_of_string(s: String) -> i32 {
let bytes = s.as_bytes();
let mut res = 0;
for i in 0..bytes.len() - 1 {
res += (bytes[i] as i32 - bytes[i + 1] as i32).abs();
}
res
}
}
```
``` ruby []
def score_of_string(s)
res = 0
for i in 0...s.length - 1
res += (s[i].ord - s[i + 1].ord).abs
end
res
end
```
---
# 🎓 Bonus Pro level Python Code:
``` python
# from itertools import pairwise
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(ord(ch1) - ord(ch2)) for ch1, ch2 in pairwise(s))
```
---
# Please consider giving me an Upvote!

| 12 | 1 | ['String', 'Iterator', 'C++', 'Java', 'Python3', 'Rust', 'Ruby', 'Kotlin', 'JavaScript', 'C#'] | 6 |
score-of-a-string | [Java / Python 3] Time O(n) space O(1) codes | java-python-3-time-on-space-o1-codes-by-nvgi4 | \njava\n public int scoreOfString(String s) {\n int score = 0;\n for (int i = 1; i < s.length(); ++i) {\n score += Math.abs(s.charAt | rock | NORMAL | 2024-04-13T16:05:55.068601+00:00 | 2024-04-13T16:05:55.068631+00:00 | 693 | false | \n```java\n public int scoreOfString(String s) {\n int score = 0;\n for (int i = 1; i < s.length(); ++i) {\n score += Math.abs(s.charAt(i) - s.charAt(i - 1));\n }\n return score;\n }\n```\n```python\n def scoreOfString(self, s: str) -> int:\n return sum(abs(ord(x) - ord(y)) for x, y in pairwise(s))\n```\n | 12 | 0 | [] | 3 |
score-of-a-string | Simple java solution | simple-java-solution-by-siddhant_1602-jwcv | Complexity\n- Time complexity: O(n) \n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public int scoreOfString(String s) {\n int val=0;\n | Siddhant_1602 | NORMAL | 2024-04-13T16:03:13.441936+00:00 | 2024-04-13T16:03:13.441969+00:00 | 1,243 | false | # Complexity\n- Time complexity: $$O(n)$$ \n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n int val=0;\n for(int i=0;i<s.length()-1;i++)\n {\n char c=s.charAt(i);\n char d=s.charAt(i+1);\n val=val+Math.abs(c-d);\n }\n return val;\n }\n}\n``` | 11 | 0 | ['Java'] | 2 |
score-of-a-string | 💯✅🔥Easy Java ,Python3 and C++ Solution|| 1 ms ||≧◠‿◠≦✌ | easy-java-python3-and-c-solution-1-ms-_-e0f0e | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this approach is that the score of a string is directly proportion | suyalneeraj09 | NORMAL | 2024-06-01T00:30:15.252748+00:00 | 2024-06-01T00:30:15.252777+00:00 | 1,882 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this approach is that the score of a string is directly proportional to the sum of the absolute differences between adjacent characters. By iterating through the string and calculating the absolute difference between each pair of adjacent characters, we can obtain the total score of the string.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe provided code calculates the score of a given string s based on the absolute difference between adjacent characters in the string. The score is calculated by iterating through the string and adding the absolute difference between each pair of adjacent characters.\n# Complexity\n- Time complexity:O(n), where n is the length of the input string s\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int scoreOfString(String s) {\n int res = 0;\n \n for(int i=0;i<s.length()-1;i++){\n res += Math.abs(s.charAt(i) - s.charAt(i+1));\n }\n return res;\n }\n}\n```\n```python3 []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n ans = 0\n \n for i in range(len(s)-1):\n ans += abs(ord(s[i]) - ord(s[i+1]))\n \n return ans\n```\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int ans = 0;\n \n for(int i = 0; i < s.length() - 1; i++) {\n ans += abs(s[i] - s[i+1]);\n }\n \n return ans;\n }\n};\n```\n\n\n | 10 | 0 | ['String', 'C++', 'Java', 'Python3'] | 9 |
score-of-a-string | [Rust] true one-liner | rust-true-one-liner-by-tmtappr-rv0u | Approach\nA windowing iterator over the byte array representing the string is created. A map iterator producing the absolute difference of each adjacent pair of | tmtappr | NORMAL | 2024-06-01T02:25:02.319900+00:00 | 2024-06-01T02:39:53.732203+00:00 | 203 | false | # Approach\nA windowing iterator over the byte array representing the string is created. A map iterator producing the absolute difference of each adjacent pair of bytes is created, then `.sum()` is invoked on it to produce the sum of differences.\n\nThis is an actual "one-liner". I see a lot of solutions (to other problems) declaring themselves "one-liners" where combinator methods are tacked on to the ends of each other one after the other going on for 10 or more lines of code. Those are not "one-liners".\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n``` rust\nimpl Solution {\n pub fn score_of_string(s: String) -> i32 {\n s.as_bytes().windows(2).map(|a| a[0].abs_diff(a[1]) as i32).sum()\n }\n}\n``` | 9 | 0 | ['Rust'] | 0 |
score-of-a-string | Python 3 || 2 lines, pairwise || T/S: 99% / 93% | python-3-2-lines-pairwise-ts-99-93-by-sp-t4h0 | \nclass Solution:\n def scoreOfString(self, s: str) -> int:\n\n absdiff = lambda x: abs(ord(x[0]) - ord(x[1]))\n\n return sum(map(absdiff,pairw | Spaulding_ | NORMAL | 2024-04-13T16:23:37.201165+00:00 | 2024-06-12T05:43:07.384448+00:00 | 782 | false | ```\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n\n absdiff = lambda x: abs(ord(x[0]) - ord(x[1]))\n\n return sum(map(absdiff,pairwise(s)))\n```\n[https://leetcode.com/problems/score-of-a-string/submissions/1231356748/](https://leetcode.com/problems/score-of-a-string/submissions/1231356748/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1), in which *N* ~ `len(s)`. | 9 | 0 | ['Python3'] | 0 |
score-of-a-string | Best approach solution (for gen alpha fr fr) | best-approach-solution-for-gen-alpha-fr-bjhcc | Intuitionbeginner friendly (especially gen alpha)ApproachbraincellComplexity
Time complexity:
O(1)
Space complexity:
O(your brain)
Code | eQfHNpKjdl | NORMAL | 2025-04-01T08:06:50.243704+00:00 | 2025-04-01T08:06:50.243704+00:00 | 143 | false | # Intuition
beginner friendly (especially gen alpha)
# Approach
braincell
# Complexity
- Time complexity:
O(1)
- Space complexity:
O(your brain)
# Code
```cpp []
typedef int skibidi;
typedef string rizz;
using edging = vector<skibidi>;
using muhahaha = vector<edging>;
istream& gooning = cin;
ostream& ohio = cout;
#define fanumtax for
#define looksmaxxing push_back
#define aura pop_back
#define sigma max_element
#define apple begin
#define endofthegrind end
#define crashout return
#define ishowspeed class
#define goon public
#define alpha size
#define zeroaura 0
#define hawk if
#define tuah else
#define superidol abs
#define Tob_Tobi_Tob_Tob_Tobi_Tob 1
ishowspeed Solution {
goon:
skibidi scoreOfString(rizz baby_gronk) {
skibidi grind = zeroaura;
fanumtax (skibidi diddy = zeroaura;diddy<baby_gronk.alpha()-Tob_Tobi_Tob_Tob_Tobi_Tob;diddy++) {
grind += superidol(baby_gronk[diddy]-baby_gronk[diddy+Tob_Tobi_Tob_Tob_Tobi_Tob]);
}
crashout grind;
}
};
``` | 8 | 0 | ['C++'] | 5 |
score-of-a-string | Simple Java solution | simple-java-solution-by-ydvaaman-8fj1 | \nclass Solution {\n public int scoreOfString(String s) {\n int sum = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n sum += Math. | ydvaaman | NORMAL | 2024-04-13T16:01:08.937757+00:00 | 2024-04-13T16:01:08.937779+00:00 | 937 | false | ```\nclass Solution {\n public int scoreOfString(String s) {\n int sum = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n sum += Math.abs((s.charAt(i) - \'0\') - (s.charAt(i + 1) - \'0\'));\n }\n return sum;\n }\n}\n``` | 8 | 1 | ['Java'] | 3 |
score-of-a-string | C++ beats 100% | c-beats-100-by-deleted_user-c1n4 | C++ beats 100%\n\n\n\n# Code\n\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum = 0;\n for(int i = 0; i+1 <= s.size()-1;i++ | deleted_user | NORMAL | 2024-06-01T05:16:33.674513+00:00 | 2024-06-01T05:16:33.674545+00:00 | 63 | false | C++ beats 100%\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum = 0;\n for(int i = 0; i+1 <= s.size()-1;i++){\n int a = s[i];\n int b = s[i+1];\n if (a > b){\n sum += a-b;\n }\n else{\n sum += b -a;\n }\n }\n return sum;\n }\n};\n``` | 7 | 0 | ['C++'] | 0 |
score-of-a-string | Python | Easy | python-easy-by-khosiyat-1o5d | see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n score = 0\n for i in range(1, | Khosiyat | NORMAL | 2024-06-01T05:36:58.199483+00:00 | 2024-06-01T05:36:58.199514+00:00 | 318 | false | [see the Successfully Accepted Submission](https://leetcode.com/problems/score-of-a-string/submissions/1273862859/?source=submission-ac)\n\n# Code\n```\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n score = 0\n for i in range(1, len(s)):\n score += abs(ord(s[i]) - ord(s[i - 1]))\n return score\n\n```\n | 6 | 0 | ['Python3'] | 0 |
score-of-a-string | Java beats 100% | java-beats-100-by-deleted_user-43b5 | Java beats 100%\n\n\n\n# Code\n\nclass Solution {\n public int scoreOfString(String s) {\n return iterateString(0,s); \n }\n\n public static i | deleted_user | NORMAL | 2024-06-01T05:18:24.692644+00:00 | 2024-06-01T05:18:24.692681+00:00 | 47 | false | Java beats 100%\n\n\n\n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n return iterateString(0,s); \n }\n\n public static int iterateString(int n, String s){\n if(n == s.length() -1 )\n return 0;\n return Math.abs(s.charAt(n) - s.charAt(n+1)) + iterateString(n+1, s);\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
score-of-a-string | ✅EASY AND SIMPLE SOLUTION✅(Beats 100.00% of users with C++) | easy-and-simple-solutionbeats-10000-of-u-yevb | \n\n# Code\n\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int score = 0;\n \n\n for(int i=0; i<s.size()-1; i++){\n | deleted_user | NORMAL | 2024-06-01T03:53:52.497135+00:00 | 2024-06-01T04:00:55.388058+00:00 | 334 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int score = 0;\n \n\n for(int i=0; i<s.size()-1; i++){\n if(int(s[i]) > int(s[i+1])){\n score = score + int(s[i]) - int(s[i+1]);\n } else {\n score = score + int(s[i+1]) - int(s[i]);\n }\n }\n return score;\n }\n};\n``` | 6 | 0 | ['C++'] | 1 |
score-of-a-string | 100% Beats || Simple CPP Solution || Anyone Will Understand | 100-beats-simple-cpp-solution-anyone-wil-rocr | Intuition\nThe problem asks for finding the score of a string based on the absolute difference between consecutive characters in the string.\n\n# Approach\nTo s | Its_Shojib | NORMAL | 2024-06-01T02:40:31.651816+00:00 | 2024-06-01T02:40:31.651834+00:00 | 2,573 | false | # Intuition\nThe problem asks for finding the score of a string based on the absolute difference between consecutive characters in the string.\n\n# Approach\nTo solve this problem, we can iterate through the string and calculate the absolute difference between each character and its consecutive character. We\'ll accumulate these differences to get the final score of the string.\n\n# Complexity\nTime complexity: ( O(n) ), where ( n ) is the length of the string s. We iterate through the string once.\nSpace complexity: ( O(1) ). We use only a constant amount of extra space.\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int count =0;\n for(int i=0; i<s.size()-1;i++){\n count = count+ abs(s[i]-s[i+1]);\n }\n return count;\n }\n};\n``` | 6 | 1 | ['C++'] | 4 |
score-of-a-string | 📌 Easy Solution with Python / C / C++ | easy-solution-with-python-c-c-by-umutert-gbp8 | Intuition 🤔The goal is to calculate a “score” for the given string s, which is the sum of the absolute differences between the ASCII values of consecutive chara | umutertugrul | NORMAL | 2025-01-19T11:18:52.800282+00:00 | 2025-01-19T11:18:52.800282+00:00 | 738 | false | # Intuition 🤔
The goal is to calculate a “score” for the given string s, which is the sum of the absolute differences between the ASCII values of consecutive characters in the string. The task involves comparing adjacent characters, converting them to their ASCII values, and summing up the differences.
# Approach 💡
- Iterate through the string, comparing each character $$s[i]$$ with the next one $$s[i+1]$$
- Compute the ASCII value of both characters using ord() (or type casting in C/C++).
# Complexities ⏳
- Time complexity: $$O(n)$$, where n is the length of the string. Each character is processed once.
- Space complexity: $$O(1)$$, as only a few variables are used, regardless of the string length.
# Code
```python3 []
class Solution:
def scoreOfString(self, s: str) -> int:
N = len(s)
total = 0
for i in range(N-1):
total += abs(ord(s[i]) - ord(s[i+1]))
return total
```
```C []
int scoreOfString(char* s) {
int total = 0;
for (int i = 0; s[i+1] != '\0'; i++)
total += abs((int)s[i] - (int)s[i + 1]);
return total;
}
```
```C++ []
class Solution {
public:
int scoreOfString(string s) {
int N = s.length();
int total = 0;
for (int i = 0; i < N-1; i++) {
total += abs((int)s[i] - (int)s[i + 1]);
}
return total;
}
};
``` | 5 | 0 | ['C', 'C++', 'Python3'] | 0 |
score-of-a-string | 💯JAVA Solution Explained in HINDI | java-solution-explained-in-hindi-by-the_-5064 | https://youtu.be/7cH7OZhUJrE\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote | The_elite | NORMAL | 2024-06-01T05:01:19.725562+00:00 | 2024-06-01T05:01:19.725590+00:00 | 1,694 | false | https://youtu.be/7cH7OZhUJrE\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote the solution if you liked it.\n\n# Subscribe:- [ReelCoding](https://www.youtube.com/@reelcoding?sub_confirmation=1)\n\nSubscribe Goal:- 500\nCurrent Subscriber:- 403\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n \n int ans = 0;\n\n for(int i = 0; i < s.length()-1; i++) {\n ans += Math.abs(s.charAt(i) - s.charAt(i + 1));\n }\n return ans;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
score-of-a-string | Easy C++ Solution | Linear Time | Constant Space | Beats 100 💯✅ | easy-c-solution-linear-time-constant-spa-tl27 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to compute a score for a given string s, which is defined as the sum of the | shobhitkushwaha1406 | NORMAL | 2024-06-01T03:20:35.353660+00:00 | 2024-06-01T03:20:35.353685+00:00 | 283 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to compute a score for a given string `s`, which is defined as the sum of the absolute differences between the ASCII values of consecutive characters in the string.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialize a sum variable to 0**: This will store the cumulative score of the string.\n2. **Iterate through the string**: Loop through the string from the first character to the second-to-last character.\n3. **Compute absolute differences**: For each character, compute the absolute difference between its ASCII value and the ASCII value of the next character.\n4. **Update the sum**: Add this difference to the sum variable.\n5. **Return the sum**: Once the loop is complete, return the sum as the final score.\n\n# Complexity\n- Time complexity: $$O(n)$$: The algorithm processes each character in the string exactly once. The main loop runs `n-1` times where `n` is the length of the string. Thus, the time complexity is linear with respect to the length of the string.\n\n- Space complexity: $$O(1)$$: The algorithm uses a constant amount of space regardless of the size of the input string. The only additional memory used is for the integer variables (`sum` and `n`), which do not depend on the length of the string.\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum=0;\n int n=s.size();\n for(int i=0;i<n-1;i++)\n sum+=abs(s[i]-s[i+1]);\n return sum;\n }\n};\n``` | 5 | 0 | ['String', 'C++'] | 2 |
score-of-a-string | simple and easy understand solution | simple-and-easy-understand-solution-by-s-keb6 | if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n int scoreOfString(string s) \n {\n int res = 0, n = s | shishirRsiam | NORMAL | 2024-04-13T18:26:13.456442+00:00 | 2024-04-13T18:26:13.456465+00:00 | 702 | false | # if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) \n {\n int res = 0, n = s.size();\n for(int i=0;i<n-1;i++)\n res += abs((s[i]-\'a\') - (s[i+1]-\'a\')); \n return res;\n }\n};\n``` | 5 | 0 | ['String', 'C', 'C++', 'Java', 'C#'] | 6 |
score-of-a-string | Yes, It's that easy 🤗🤗 | yes-its-that-easy-by-utkarshpriyadarshi5-qwa6 | Welcome, I hope you like this Solution \uD83E\uDD17\uD83E\uDD17\n# Approach\n1. Character Differences:\n\n - Imagine each letter as having a number associate | utkarshpriyadarshi5026 | NORMAL | 2024-06-01T10:47:44.822405+00:00 | 2024-06-01T10:47:44.822437+00:00 | 707 | false | # Welcome, I hope you like this Solution \uD83E\uDD17\uD83E\uDD17\n# Approach\n1. `Character Differences:`\n\n - Imagine each letter as having a number associated with it (its position in the alphabet). \'a\' is 1, \'b\' is 2, and so on. \n - The code looks at each pair of neighboring letters and finds the difference between their numbers. For example, the difference between \'b\' and \'a\' is 1, and the difference between \'c\' and \'b\' is also 1.\n\n2. `Absolute Differences:`\n\n - Sometimes, differences can be negative (e.g., \'a\' - \'b\' = -1). We don\'t want negative values, so we use a special function called abs (short for absolute value) to make all the differences positive. So, even if \'a\' - \'b\' is -1, the abs function turns it into 1.\n3. `Adding Up the Differences:`\n\n - The code keeps a running total of all these positive differences. This total is the "score" of the string. A higher score means the letters in the string are more spread out in the alphabet.\n\n# Complexity\n- **Time complexity:**\n**The time complexity of this function is $$O(n)$$, where \'n\' is the length of the input string s. Here\'s why:**\n\n - `Loop:` The primary work is done in the for loop, which iterates through the string once.\n\n - `Constant Operations:` Inside the loop, each iteration performs a constant amount of work.\n\n\n---\n\n\n- **Space complexity:**\n**The space complexity of this function is $$O(1)$$, which means it uses constant space. This is because:**\n\n - Fixed Variables: The function uses a fixed number of variables (score, i).\n\n - No Additional Data Structures: It doesn\'t create any data structures (like arrays or maps) whose size would depend on the input string.\n\n\n\n# Code\n\n```go []\nfunc scoreOfString(s string) int {\n score := 0\n\n for i := 1; i < len(s); i++ {\n curr := int(s[i])\n prev := int(s[i - 1])\n\n score += abs(curr - prev)\n }\n return score\n}\n\n\nfunc abs(x int) int {\n if x < 0 {\n return -x\n }\n return x\n}\n```\n```python []\ndef score_of_string(s):\n score = 0\n if len(s) <= 1:\n return score\n\n for i in range(1, len(s)):\n score += abs(ord(s[i]) - ord(s[i - 1])) # Use ord() for ASCII values\n return score\n```\n```Java []\nclass Solution {\n public static int scoreOfString(String s) {\n int score = 0;\n if (s == null || s.length() <= 1) {\n return score;\n }\n\n for (int i = 1; i < s.length(); i++) {\n score += Math.abs(s.charAt(i) - s.charAt(i - 1));\n }\n return score;\n }\n}\n```\n | 4 | 0 | ['String', 'Java', 'Go', 'Python3'] | 0 |
score-of-a-string | 0ms - Beats 100% ✅🔥🔥🔥| Python, C++💻 | SUPER EASY Approach, Explanation📕 | 0ms-beats-100-python-c-super-easy-approa-5ibl | 0ms - Beats 100% \u2705\uD83D\uDD25\uD83D\uDD25\uD83D\uDD25| Python, C++\uD83D\uDCBB | SUPER EASY Approach, Explanation\uD83D\uDCD5\n\n## 1. Proof\n Describe yo | kcp_1410 | NORMAL | 2024-06-01T07:07:45.522202+00:00 | 2024-06-01T07:07:45.522228+00:00 | 183 | false | # 0ms - Beats 100% \u2705\uD83D\uDD25\uD83D\uDD25\uD83D\uDD25| Python, C++\uD83D\uDCBB | SUPER EASY Approach, Explanation\uD83D\uDCD5\n\n## 1. Proof\n<!-- Describe your first thoughts on how to solve this problem. -->\n### 1.1. C++\n\n\n### 1.2. Python3\n\n\n## 2. Algorithms\n* Simple traversing\n\n## 3. Code (with explanation each line)\n```python3 []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n res = 0 # Initialize result variable\n for i in range(len(s) - 1): # We get i & i+1 at each index so we don\'t need to check i as the last index but i+1\n res += abs(ord(s[i]) - ord(s[i + 1])) # `ord` to get the corresponding ASCII number of adjacent characters at i & i+1, subtract them and get the absolute value\n return res # Return the final result\n```\n\n```cpp []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int res = 0;\n for (int i=0; i < s.size() - 1; i++) {\n res += abs(int(s[i]) - int(s[i + 1]));\n }\n return res;\n }\n};\n```\n\n## 4. Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n### Upvote if you find this solution helpful, thank you \uD83E\uDD0D | 4 | 0 | ['String', 'Python', 'C++', 'Python3'] | 0 |
score-of-a-string | simple solution with explanation | simple-solution-with-explanation-by-anup-12gr | Intuition\n- substract adjacent characters and add this absolute value in res\n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n | anupsingh556 | NORMAL | 2024-06-01T04:17:04.954250+00:00 | 2024-06-01T04:17:04.954288+00:00 | 203 | false | # Intuition\n- substract adjacent characters and add this absolute value in res\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: Constatnt Space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int n = s.size(), res = 0;\n for(int i=0;i<n-1;i++)res+=abs(s[i]-s[i+1]);\n return res;\n }\n};\n``` | 4 | 0 | ['C++'] | 2 |
score-of-a-string | ✅Python🔥Easy Solution🔥 Pairwise Function🔥 | pythoneasy-solution-pairwise-function-by-54us | Code\n\nclass Solution:\n def pairwise(self, iterable):\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n \n def scoreOf | KG-Profile | NORMAL | 2024-06-01T02:09:44.085371+00:00 | 2024-06-01T02:09:44.085422+00:00 | 121 | false | # Code\n```\nclass Solution:\n def pairwise(self, iterable):\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n \n def scoreOfString(self, s: str) -> int:\n absdiff = lambda x: abs(ord(x[0]) - ord(x[1]))\n return sum(map(absdiff, self.pairwise(s)))\n``` | 4 | 0 | ['Python3'] | 0 |
score-of-a-string | JAVA Easy Solution [ 99.91% ] | java-easy-solution-9991-by-rajarshimitra-uebl | Approach\n- Initialize a variable sum to keep track of the score.\n- If the input string s is empty, return 0.\n- If the length of s is 1, return the ASCII valu | RajarshiMitra | NORMAL | 2024-05-10T06:12:41.862292+00:00 | 2024-06-16T07:04:54.374448+00:00 | 15 | false | # Approach\n- Initialize a variable `sum` to keep track of the score.\n- If the input string `s` is empty, return 0.\n- If the length of `s` is 1, return the ASCII value of the only character.\n- Iterate over the characters of the string starting from the second character (index 1).\n- Calculate the absolute difference between the ASCII values of the current character and the previous character.\n- Add the absolute difference to the `sum`.\n- Return the final value of `sum` as the score of the string.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n int sum=0;\n if(s.length() == 0) return 0;\n if(s.length() == 1) return (s.charAt(0));\n for(int i=1; i<s.length(); i++){\n sum+=Math.abs((s.charAt(i-1))-(s.charAt(i)));\n }\n return sum;\n }\n}\n```\n\n\n | 4 | 0 | ['Java'] | 0 |
score-of-a-string | 0ms | 100% beat | Simple and Easy Approach | 0ms-100-beat-simple-and-easy-approach-by-i6hi | Approach\nLoop through the array and calculate difference of character at index i and i+1, loop goes all the way upto size-1, store it in varaible res and at ea | ahlyab | NORMAL | 2024-04-14T09:29:05.722779+00:00 | 2024-04-14T09:29:05.722805+00:00 | 166 | false | # Approach\nLoop through the array and calculate difference of character at index `i` and `i+1`, loop goes all the way upto `size-1`, store it in varaible `res` and at each iteration add the difference after taking it\'s `abs` to `res `\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int res = 0;\n\n for(int i=0; i<s.size()-1; ++i) {\n res += abs(s[i] - s[i+1]);\n }\n\n return res;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
score-of-a-string | 🔥✅💯Easiest C++ / Python3 🐍 / Java / C / Python ✅🔥☠️ Beats 💯 ✅ | easiest-c-python3-java-c-python-beats-by-vd4y | Intuition\n\n\n\n\n\nC++ []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int score = 0;\n for(int i = 1; i < s.length(); ++i)\n | Edwards310 | NORMAL | 2024-04-13T16:05:36.103205+00:00 | 2024-04-13T16:16:27.577630+00:00 | 305 | false | # Intuition\n\n\n\n\n\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int score = 0;\n for(int i = 1; i < s.length(); ++i)\n score += abs((int)s[i] - (int)s[i -1]);\n return score;\n }\n};\n```\n```python3 []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n score = 0\n for i in range(1 , len(s)):\n score += abs(ord(s[i]) - ord(s[i - 1]))\n return score\n```\n```C []\nint scoreOfString(char* s) {\n int score = 0;\n for(int i = 1; s[i] != \'\\0\'; ++i)\n score += abs((int)s[i] - (int)s[i -1]);\n \n return score;\n}\n```\n``` Java []\nclass Solution {\n public int scoreOfString(String s) {\n int score = 0;\n for(int i = 1; i < s.length(); ++i)\n score += Math.abs((int)s.charAt(i) - (int)s.charAt(i - 1));\n return score;\n }\n}\n```\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 Solution:\n def scoreOfString(self, s: str) -> int:\n score = 0\n for i in range(1 , len(s)):\n score += abs(ord(s[i]) - ord(s[i - 1]))\n return score\n``` | 4 | 0 | ['C', 'Python', 'C++', 'Java', 'Python3'] | 2 |
score-of-a-string | Score of a String | 0ms and 100.00% beats | score-of-a-string-0ms-and-10000-beats-by-vkfd | IntuitionThe problem requires us to compute the score of a string by summing the absolute differences between adjacent character ASCII values. We can solve this | hariharan-dev-05 | NORMAL | 2025-03-16T16:23:46.260256+00:00 | 2025-03-16T16:23:46.260256+00:00 | 240 | false | # Intuition
The problem requires us to compute the score of a string by summing the absolute differences between adjacent character ASCII values. We can solve this efficiently by iterating through the string once.
# Approach
1. Convert each character in the string to its ASCII value using `ord()`.
2. Use `zip()` to pair adjacent ASCII values.
3. Compute the absolute difference for each pair.
4. Sum up the differences to get the final score.
# Complexity
- **Time complexity:** $$O(n)$$, as we iterate through the string once.
- **Space complexity:** $$O(1)$$, since we use only a few extra variables.
# Code
```python
from itertools import pairwise
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(a - b) for a, b in zip(map(ord, s), map(ord, s[1:])))
``` | 3 | 0 | ['Python3'] | 0 |
score-of-a-string | One Linear - Clean Code | one-linear-clean-code-by-bazil_zywotow-m6u8 | null | Bazil_Zywotow | NORMAL | 2025-01-18T11:17:19.691289+00:00 | 2025-01-18T11:17:19.691289+00:00 | 234 | false |
```javascript []
const scoreOfString = (s, [first, ...tail] = [...s].map(c => c.charCodeAt(0))) =>
tail.reduce(([score, prev], v) => [score + Math.abs(prev - v), v], [0, first])[0];
``` | 3 | 0 | ['JavaScript'] | 1 |
score-of-a-string | 100% Beats | 100-beats-by-kumarrishikant660-p4mi | 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 | kumarrishikant660 | NORMAL | 2024-12-03T05:10:12.687549+00:00 | 2024-12-03T05:10:12.687585+00:00 | 225 | 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:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int n=s.size();\n int c=0;\n for(int i=0;i<n-1;i++){\n c=c+abs(s[i]-s[i+1]);\n }\n return c;\n }\n};\n\n\n``` | 3 | 0 | ['C++'] | 3 |
score-of-a-string | 100% Go | 100-go-by-kaya-sem-vece | 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\n# Complexity\n- Tim | Kaya-Sem | NORMAL | 2024-08-06T13:22:07.343527+00:00 | 2024-08-06T13:25:46.380502+00:00 | 114 | 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\n# Complexity\n- Time complexity: $\\Theta(N)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: $\\Theta(N)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfunc scoreOfString(s string) int {\n\tresult := 0\n\n\tfor i := 0; i < len(s) - 1; i++ {\n\t\tdiff := int(s[i]) - int(s[i+1])\n\n\t\tif diff < 0 {\n\t\t\tdiff = -diff\n\t\t}\n\t\tresult += diff\n\t}\n\n\treturn result\n}\n``` | 3 | 0 | ['Go'] | 1 |
score-of-a-string | Kotlin one line solution using zipWithNext | kotlin-one-line-solution-using-zipwithne-4kp8 | Intuition\nThe goal is to compute the "score" of a string, defined as the sum of absolute differences between the ASCII values of adjacent characters. This can | shtanko | NORMAL | 2024-06-01T20:10:59.819306+00:00 | 2024-06-01T20:10:59.819341+00:00 | 164 | false | # Intuition\nThe goal is to compute the "score" of a string, defined as the sum of absolute differences between the ASCII values of adjacent characters. This can be visualized as finding the "distance" between each consecutive character and summing these distances.\n\n# Approach\n - Iterate through the string and for each pair of consecutive characters, compute the absolute difference between their ASCII values.\n - Use Kotlin\'s `zipWithNext` function to create pairs of consecutive characters.\n - Apply a transformation on these pairs to calculate the absolute difference.\n - Use `sum` to aggregate these differences into a final score.\n\n# Complexity\n- Time complexity:\nThe time complexity is $$O(n)$$, where $$n$$ is the length of the string. This is because we iterate through the string once to create pairs and once more to sum the differences.\n\n- Space complexity:\n The space complexity is $$O(n)$$ because `zipWithNext` generates a list of pairs which, in the worst case, will have size $$n-1$$. Additionally, the intermediate list of differences also requires $$O(n)$$ space.\n\n# Code\n```\n\nclass Solution {\n fun scoreOfString(s: String) = s.zipWithNext { a, b -> kotlin.math.abs(a - b) }.sum()\n}\n``` | 3 | 0 | ['Kotlin'] | 0 |
score-of-a-string | [Python, Java] Elegant & Short | 1-Line | Pairwise | python-java-elegant-short-1-line-pairwis-zs6c | Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n# Code\npython []\nclass Solution:\n def scoreOfString(self, string: str) -> int:\n r | Kyrylo-Ktl | NORMAL | 2024-06-01T16:36:45.875736+00:00 | 2024-06-01T16:40:31.087640+00:00 | 364 | false | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```python []\nclass Solution:\n def scoreOfString(self, string: str) -> int:\n return sum(abs(ord(a) - ord(b)) for a, b in pairwise(string))\n```\n```java []\npublic class Solution {\n public int scoreOfString(String string) {\n return java.util.stream.IntStream.range(0, string.length() - 1).map(i -> Math.abs(string.charAt(i) - string.charAt(i + 1))).sum();\n }\n}\n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
score-of-a-string | O(n) Straight forward solution ✅ | on-straight-forward-solution-by-yousufmu-b123 | Intuition\n Describe your first thoughts on how to solve this problem. \n- We can simply traverse through the array and find absoulte difference ASCII between t | yousufmunna143 | NORMAL | 2024-06-01T13:37:12.715412+00:00 | 2024-06-01T13:37:12.715454+00:00 | 1,424 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- We can simply traverse through the array and find absoulte difference ASCII between two adjacent characters and return the sum of these differences.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Declare a variable `score` and initialize it to 0.\n- Start a loop from 1 to n, and find absolute difference between character `s[i]` and `s[i-1]` and add it to` score`.\n- Return `score`.\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution \n{\n public int scoreOfString(String s) \n {\n int score = 0;\n for(int i = 1; i < s.length(); i ++)\n {\n score += (Math.abs(s.charAt(i)-s.charAt(i-1)));\n }\n return score;\n }\n}\n``` | 3 | 0 | ['String', 'Java'] | 1 |
score-of-a-string | 100% better solution||Easy||C++ | 100-better-solutioneasyc-by-singhpayal22-lt73 | 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 | payalsingh2212 | NORMAL | 2024-06-01T11:52:11.677486+00:00 | 2024-06-01T11:52:11.677512+00:00 | 291 | 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: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int n=s.size();\n int ans=0;\n for(int i=0;i<n-1;i++){\n ans+=(abs(s[i]-s[i+1]));\n }\n return ans;//please upvote\n }\n};\n``` | 3 | 0 | ['C++'] | 2 |
score-of-a-string | Java Easy to Understand Solution with Explanation || 100% beats | java-easy-to-understand-solution-with-ex-t4gk | Intuition\n> Iterate through the string and remember the last ASCII value.\n\n# Approach\n\n\n\n1. Initialization:\n - int ans = 0;: This initializes the var | leo_messi10 | NORMAL | 2024-06-01T11:40:17.913770+00:00 | 2024-06-01T11:40:17.913833+00:00 | 43 | false | # Intuition\n> Iterate through the string and remember the last ASCII value.\n\n# Approach\n\n\n\n1. **Initialization**:\n - `int ans = 0;`: This initializes the variable `ans` to 0, which will hold the final score.\n - `int size = s.length();`: This stores the length of the input string `s`.\n - `int last = s.charAt(0);`: This initializes the `last` variable with the ASCII value of the first character in the string `s`.\n\n2. **Loop through the string**:\n - `for (int i = 1; i < size; i++)`: This loop starts from the second character (`i = 1`) and iterates through the rest of the string.\n - `ans += Math.abs(s.charAt(i) - last);`: For each character in the string (starting from the second character), the absolute difference between the ASCII values of the current character and the `last` character is calculated and added to `ans`.\n - `last = s.charAt(i);`: The `last` variable is then updated to the current character for the next iteration.\n\n3. **Return the result**:\n - `return ans;`: After the loop completes, the total score `ans` is returned.\n\n### Example\n\nConsider the input string `s = "abc"`:\n\n1. Initial values:\n - `ans = 0`\n - `size = 3`\n - `last = \'a\'` (ASCII value 97)\n\n2. First iteration (`i = 1`):\n - Current character: `s.charAt(1) = \'b\'` (ASCII value 98)\n - `ans += Math.abs(98 - 97) = 1`\n - Update `last = \'b\'`\n\n3. Second iteration (`i = 2`):\n - Current character: `s.charAt(2) = \'c\'` (ASCII value 99)\n - `ans += Math.abs(99 - 98) = 1`\n - Update `last = \'c\'`\n\n4. Final value:\n - `ans = 1 + 1 = 2`\n\nSo, the method would return `2` for the input string `"abc"`.\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n int ans = 0;\n int size = s.length();\n int last = s.charAt(0);\n\n for (int i = 1; i < size; i++) {\n ans += Math.abs(s.charAt(i) - last);\n last = s.charAt(i);\n }\n\n return ans;\n }\n}\n```\n\n\n | 3 | 0 | ['String', 'Java'] | 1 |
score-of-a-string | NO BRAINING AT ALL | no-braining-at-all-by-nurliaidin-2gdn | 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 | Nurliaidin | NORMAL | 2024-06-01T10:41:34.358996+00:00 | 2024-06-01T10:41:34.359020+00:00 | 234 | 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$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code\n``` javascript []\nvar scoreOfString = function(s) {\n let sum = 0;\n let prev = s.charCodeAt(0) \n for(let i=1; i<s.length; i++) {\n sum += Math.abs(prev - s.charCodeAt(i));\n prev = s.charCodeAt(i);\n }\n return sum;\n};\n```\n``` cpp []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum = 0;\n int prev = s[0];\n for(int i=1; i<s.size(); i++) {\n sum += abs(prev - s[i]);\n prev = s[i];\n }\n return sum;\n }\n};\n``` | 3 | 0 | ['String', 'C++', 'JavaScript'] | 0 |
score-of-a-string | Scala: fold by indices | scala-fold-by-indices-by-serhiyshaman-rv7m | Code\n\nobject Solution {\n def scoreOfString(s: String): Int = \n (1 until s.length).foldLeft(0)((sum, i) => sum + (s(i - 1) - s(i)).abs)\n}\n | SerhiyShaman | NORMAL | 2024-06-01T06:12:25.976975+00:00 | 2024-06-01T06:12:25.977003+00:00 | 40 | false | # Code\n```\nobject Solution {\n def scoreOfString(s: String): Int = \n (1 until s.length).foldLeft(0)((sum, i) => sum + (s(i - 1) - s(i)).abs)\n}\n``` | 3 | 0 | ['Scala'] | 0 |
score-of-a-string | Easy C++ Solution | easy-c-solution-by-atharav_s-uwng | Video Explanation\nhttps://youtu.be/PgW73G4Um8I?si=E311v3I4mf52lNE9\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe task is to c | Atharav_s | NORMAL | 2024-06-01T04:25:49.386840+00:00 | 2024-06-01T04:25:49.386869+00:00 | 1,434 | false | # Video Explanation\nhttps://youtu.be/PgW73G4Um8I?si=E311v3I4mf52lNE9\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe task is to compute the "score" of a given string based on the absolute differences between the ASCII values of consecutive characters. The idea is to measure how different each character is from the next in terms of their ASCII values and sum these differences to get the final score.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a variable sum to store the cumulative score.\n2. Loop through the string from the first character to the second-to-last character.\n3. For each character at position i, calculate the absolute difference between the ASCII values of the character at i and i+1.\n4. Add this difference to sum.\n5. After the loop ends, return sum as the score of the string.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum=0;\n for(int i=0;i<s.size()-1;i++){\n sum+=abs(s[i]-s[i+1]);\n }\n return sum;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
score-of-a-string | JAVA || EASYY || WITH EXPLANATION || BEATS 99.87% 🔥 | java-easyy-with-explanation-beats-9987-b-emi3 | Intuition\nWe can iterate over each character using for loop. Calculate absolute differnce between each adjacent character and add it to sum.\n\n# Approach\n1) | avnisinngh | NORMAL | 2024-06-01T01:19:49.735220+00:00 | 2024-06-01T01:19:49.735240+00:00 | 164 | false | # Intuition\nWe can iterate over each character using for loop. Calculate absolute differnce between each adjacent character and add it to sum.\n\n# Approach\n1) Create Variables `sum` to store the total sum , `first`to store the value of first element and `scnd` to store the value of second element.\n2) For loop starting from `index 0` to `s.length()-1`\n - `int first = (int)(s.charAt(i))` store ASCII value of 1st char\n - `int scnd = (int)(s.charAt(i+1))` store ASCII value of 2nd char\n - `sum += Math.abs(first-scnd)` to calculate the absolute difference between first and second character and add it to sum \n3) Return `sum`\n\n\n# Complexity\n- Time complexity:**O(n)** where n is the length of the input string s.\n- Space complexity:**O(1)** as only a constant amount of extra space is used\n\n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n int sum = 0;\n for(int i = 0;i<s.length()-1;i++) {\n int first = (int)(s.charAt(i));\n int scnd = (int)(s.charAt(i+1));\n sum += Math.abs(first-scnd);\n }\n return sum;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
score-of-a-string | JavaScript Solution | Simple | javascript-solution-simple-by-pranav_rao-a5z0 | Approach\n Describe your approach to solving the problem. \nWe Iterate over each letter of the string and find its ASCII character using the charCodeAt function | pranav_rao_97 | NORMAL | 2024-05-06T16:17:45.978678+00:00 | 2024-05-06T16:17:45.978709+00:00 | 239 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nWe Iterate over each letter of the string and find its ASCII character using the `charCodeAt` function.\nWe then subtract `s[i + 1]` from `s[i]` and then get its absolute value using `Math.abs()`.\nWe then add this value to `sum` and store the result in `sum`.\nFinally we return `sum`. \n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @return {number}\n */\nvar scoreOfString = function (s) {\n let sum = 0;\n for (let i = 0; i < s.length - 1; i++) {\n sum += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1));\n }\n\n return sum;\n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
score-of-a-string | ✅✅Beats 100% | Beginner Friendly 💯 | beats-100-beginner-friendly-by-viresh_de-da1q | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. \n\n -->\n\n\n\n\n\n\n\n\n\n\n# Code\npython []\nclass Solution:\n def scoreOf | viresh_dev | NORMAL | 2024-04-13T16:15:29.458079+00:00 | 2024-04-13T16:15:29.458103+00:00 | 602 | false | <!-- # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n<!-- # Approach --> -->\n\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```python []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n res=0\n for i in range(1,len(s)):\n res+=abs(ord(s[i]) - ord(s[i-1]))\n return res\n``` | 3 | 0 | ['Python3'] | 1 |
score-of-a-string | 🔥Beats 100% - Brute Force | Clean Code | C++ | | beats-100-brute-force-clean-code-c-by-an-p4g9 | Code\n\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int res = 0;\n for (int i = 1; i < s.size(); i++)\n {\n r | Antim_Sankalp | NORMAL | 2024-04-13T16:07:45.416468+00:00 | 2024-04-13T16:07:45.416498+00:00 | 552 | false | # Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int res = 0;\n for (int i = 1; i < s.size(); i++)\n {\n res += abs(s[i] - s[i - 1]);\n }\n\n return res;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
score-of-a-string | Easiest Java Solution | easiest-java-solution-by-1asthakhushi1-b3wv | \n\n# Code\n\nclass Solution {\n public int scoreOfString(String s) {\n int sum=0;\n for(int i=1;i<s.length();i++)\n sum+=Math.abs(( | 1asthakhushi1 | NORMAL | 2024-04-13T16:06:25.701887+00:00 | 2024-04-13T16:07:29.753237+00:00 | 251 | false | \n\n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n int sum=0;\n for(int i=1;i<s.length();i++)\n sum+=Math.abs((int)s.charAt(i)-(int)s.charAt(i-1));\n return sum;\n }\n}\n``` | 3 | 0 | ['Java'] | 3 |
score-of-a-string | Score of a String | score-of-a-string-by-bear001-tqa8 | IntuitionThe problem requires calculating the sum of the absolute differences between the ASCII values of adjacent characters in a given string. Since the absol | BEAR001 | NORMAL | 2025-03-29T18:13:32.369715+00:00 | 2025-03-29T18:13:32.369715+00:00 | 64 | false | # **Intuition**
The problem requires calculating the sum of the absolute differences between the ASCII values of adjacent characters in a given string. Since the absolute difference measures how far apart two values are, we can efficiently solve this by iterating through the string and summing up these differences.
---
# **Approach**
1. Initialize a variable `Ret` to store the cumulative score.
2. Loop through the string from index 0 to `len(s) - 2` (to avoid index out-of-bounds error).
3. For each index `i`, calculate the absolute difference between the ASCII values of `s[i]` and `s[i + 1]` using `ord()` and add it to `Ret`.
4. Return the final value of `Ret` as the score.
This approach leverages a single loop, making it efficient for strings of length up to 100.
---
# **Complexity Analysis**
- **Time Complexity:** $$O(n)$$
We iterate through the string exactly once, where \( n \) is the length of the string.
- **Space Complexity:** $$O(1)$$
The solution uses a constant amount of space regardless of the input size.
---
# Code
```python3 []
class Solution:
def scoreOfString(self, s: str) -> int:
Ret = 0
for i in range(len(s) - 1):
Ret += abs(ord(s[i]) - ord(s[i + 1]))
return Ret
``` | 2 | 0 | ['String', 'Python3'] | 0 |
score-of-a-string | Easy java solution.. Beats 99% | easy-java-solution-beats-99-by-krishn13-hs5v | IntuitionThe problem requires calculating the total difference between consecutive characters in a string. My first thought was to iterate through the string an | krishn13 | NORMAL | 2025-03-14T13:10:01.070548+00:00 | 2025-03-14T13:10:01.070548+00:00 | 228 | false |
# Intuition
The problem requires calculating the total difference between consecutive characters in a string. My first thought was to iterate through the string and compute the absolute difference between adjacent characters.
# Approach
1. Initialize a variable `sum` to store the total score.
2. Iterate through the string from index `0` to `s.length() - 2`.
3. For each character, compute the absolute difference between it and the next character.
4. Add this difference to `sum`.
5. Finally, return the accumulated `sum`.
# Complexity
- **Time complexity:** \(O(n)\) — Since we traverse the string once, where \(n\) is the length of the string.
- **Space complexity:** \(O(1)\) — We use only a single integer variable to store the result, so extra space usage is constant.
---
# Code
```java []
class Solution {
public int scoreOfString(String s) {
int sum = 0;
for(int i = 0;i < s.length()-1;i++)
{
sum += Math.abs(s.charAt(i) - s.charAt(i+1));
}
return sum;
}
}
``` | 2 | 0 | ['Java'] | 0 |
score-of-a-string | Beats 100% ✅C++ Easy to Understand | beats-100-c-easy-to-understand-by-dsxoin-81kp | Complexity
Time complexity: O(N)
Space complexity: O(1)
Code | DSxoiN9NK0 | NORMAL | 2025-02-05T16:35:37.371084+00:00 | 2025-02-05T16:35:37.371084+00:00 | 120 | false | # Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int scoreOfString(string s) {
int answer = 0;
for(int i = 0; i < s.size() - 1; i++){
int sum = 0;
sum = abs(s[i] - s[i+1]);
answer += sum;
}
return answer;
}
};
``` | 2 | 0 | ['C++'] | 0 |
score-of-a-string | ✅ Easiest One Liner || Beats 100% 😉 | easiest-one-liner-beats-100-by-karan_agg-c11e | Code\ncpp []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int ans=0;\n for(int i=0;i<s.length()-1;i++) ans+=abs(s[i]-s[i+1]);\n | Karan_Aggarwal | NORMAL | 2024-10-07T13:36:10.525054+00:00 | 2024-10-07T13:36:10.525085+00:00 | 2 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int ans=0;\n for(int i=0;i<s.length()-1;i++) ans+=abs(s[i]-s[i+1]);\n return ans;\n }\n};\n```\n# Upvote ? \uD83D\uDE0A | 2 | 0 | ['String', 'C++'] | 0 |
score-of-a-string | JAVA SOLUTION-BEATS 99%-SINGLE LINE SOLUTION | java-solution-beats-99-single-line-solut-8ao3 | \n\n# Code\njava []\nclass Solution {\n public int scoreOfString(String s) {\n int res=0;\n for(int i=0;i<s.length()-1;i++){\n res+= | THANMAYI01 | NORMAL | 2024-09-18T18:22:51.191731+00:00 | 2024-09-18T18:22:51.191768+00:00 | 359 | false | \n\n# Code\n```java []\nclass Solution {\n public int scoreOfString(String s) {\n int res=0;\n for(int i=0;i<s.length()-1;i++){\n res+=Math.abs((s.charAt(i)-s.charAt(i+1)));\n }\n return res;\n }\n}\n``` | 2 | 0 | ['String', 'Java'] | 1 |
score-of-a-string | Python easy ULTRA PRO MAX Solution | python-easy-ultra-pro-max-solution-by-mi-ro0g | Code\npython3 []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n out = 0\n for i in range(len(s) - 1):\n out += abs(ord | midhun98 | NORMAL | 2024-08-22T14:04:38.579053+00:00 | 2024-08-23T09:21:02.468085+00:00 | 247 | false | # Code\n```python3 []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n out = 0\n for i in range(len(s) - 1):\n out += abs(ord(s[i]) - ord(s[i + 1]))\n return out``` | 2 | 0 | ['Python3'] | 3 |
score-of-a-string | C# Solution for Score of a String Problem | c-solution-for-score-of-a-string-problem-c7kp | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires calculating a score for a string based on the absolute differences | Aman_Raj_Sinha | NORMAL | 2024-06-01T19:16:22.944262+00:00 | 2024-06-01T19:16:22.944292+00:00 | 236 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires calculating a score for a string based on the absolute differences between the ASCII values of adjacent characters. The intuition here is to iterate through the string, compute these differences, and accumulate them to get the final score.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tInitialization: Start by initializing a variable score to 0, which will keep track of the total score.\n2.\tIteration: Loop through the string from the first character to the second last character.\n3.\tCompute Differences: For each character, calculate the absolute difference between its ASCII value and the ASCII value of the next character.\n4.\tAccumulate Score: Add this difference to the score.\n5.\tReturn Result: After processing all pairs of adjacent characters, return the accumulated score.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(n), where n is the length of the string. This is because we are iterating through the string once, performing a constant amount of work (computing the difference and adding it to the score) for each pair of adjacent characters.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this solution is O(1). We are only using a fixed amount of extra space (the score variable) regardless of the input size.\n\n# Code\n```\npublic class Solution {\n public int ScoreOfString(string s) {\n int score = 0;\n // Iterate through the string from the first to the second last character\n for (int i = 0; i < s.Length - 1; i++) {\n // Calculate the absolute difference between adjacent characters\n int diff = Math.Abs(s[i] - s[i + 1]);\n // Add the difference to the score\n score += diff;\n }\n return score;\n }\n}\n``` | 2 | 0 | ['C#'] | 0 |
score-of-a-string | 3110. Score of a String | 3110-score-of-a-string-by-sounak_12-kmsf | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n\nThe given C++ function scoreOfString calculates a specific score for a | Sounak_12 | NORMAL | 2024-06-01T18:57:11.246045+00:00 | 2024-06-01T18:57:11.246081+00:00 | 208 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n\nThe given C++ function scoreOfString calculates a specific score for a given string s. Here is a step-by-step description of the approach:\n\nFunction Signature:\n\nThe function scoreOfString takes a single argument, a string s, and returns an integer representing the score.\nInitialization:\n\nAn integer variable ans is initialized to 0. This variable will store the cumulative score as the function processes the string.\nIteration Through the String:\n\nA for loop iterates through the string s from the first character to the second-to-last character (i.e., i ranges from 0 to s.length()-2). The loop ensures that each character except the last one is considered for the scoring process.\nScore Calculation:\n\nWithin the loop, the absolute difference between the ASCII values of the current character s[i] and the next character s[i+1] is computed using the abs function.\nThis absolute difference is then added to the ans variable.\nReturn the Result:\n\nAfter the loop completes, the function returns the accumulated score stored in ans.\nExample Walkthrough\nLet\'s go through an example to illustrate how the function works:\n\nExample Input: "abcd"\n\nThe function initializes ans to 0.\nThe loop iterates over the string:\nFor i = 0, s[0] = \'a\' and s[1] = \'b\'. The absolute difference is abs(\'a\' - \'b\') = abs(97 - 98) = 1. ans is updated to 1.\nFor i = 1, s[1] = \'b\' and s[2] = \'c\'. The absolute difference is abs(\'b\' - \'c\') = abs(98 - 99) = 1. ans is updated to 2.\nFor i = 2, s[2] = \'c\' and s[3] = \'d\'. The absolute difference is abs(\'c\' - \'d\') = abs(99 - 100) = 1. ans is updated to 3.\nThe loop ends since there are no more characters to process.\nThe function returns the final score 3.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- the overall time complexity of the scoreOfString function is \n\uD835\uDC42(\uD835\uDC5B), where n is the length of the input string s. This indicates that the function runs in linear time relative to the size of the input.\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 : C++\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int ans = 0;\n for(int i=0;i<s.length()-1;i++)\n {\n ans+=abs(s[i]-s[i+1]);\n }\n return ans;\n }\n};\n```\n# Code : Python\n```\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n ans = 0\n for i in range(len(s)-1):\n ans+=abs(ord(s[i])-ord(s[i+1]))\n return ans\n```\n | 2 | 0 | ['C++', 'Python3'] | 0 |
score-of-a-string | Easy and Effective Solution for Question: #3110 | easy-and-effective-solution-for-question-iah8 | Intuition\nHere for this question, we iterate through the characters of the string s and calculate the absolute difference between the ASCII values of adjacent | LaFlameX07 | NORMAL | 2024-06-01T16:56:11.641227+00:00 | 2024-06-01T16:56:11.641250+00:00 | 160 | false | # Intuition\nHere for this question, we iterate through the characters of the string s and calculate the absolute difference between the ASCII values of adjacent characters. Then, we sum up these absolute differences to get the score of the string.\n# Approach\nBelow code defines a class Solution with a method scoreOfString that takes a string s as input and returns its score. It iterates through the characters of the string and calculates the absolute difference between the ASCII values of adjacent characters, then sums up these differences to obtain the score.\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def scoreOfString(self, s):\n score = 0\n for i in range(1, len(s)):\n score += abs(ord(s[i]) - ord(s[i - 1]))\n return score\n``` | 2 | 0 | ['Python'] | 1 |
score-of-a-string | Beats 100% || abs() function || C++ | beats-100-abs-function-c-by-batmen-wz6p | \n\n# Intuition\nabs() function is used to get absolute difference between each character and its next\n\n# Approach\nRemember to iterate only till n-2, since w | peakfor | NORMAL | 2024-06-01T12:51:01.668777+00:00 | 2024-06-01T12:54:58.694884+00:00 | 0 | false | \n\n# Intuition\nabs() function is used to get absolute difference between each character and its next\n\n# Approach\nRemember to iterate only till n-2, since we we will be using i+1 index which WILL cause out of bounds if we dont limit loop till n-2\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int score=0;\n for(int i=0; i<s.size()-1; i++){\n score=score+abs(s[i]-s[i+1]);\n }\n return score;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
score-of-a-string | Kotlin one line solution | kotlin-one-line-solution-by-reosfire-ssq9 | Code\n\nclass Solution {\n fun scoreOfString(s: String) = s.indices.reduce { acc, i -> acc + abs(s[i] - s[i - 1]) }\n}\n | reosfire | NORMAL | 2024-06-01T11:09:19.202980+00:00 | 2024-06-01T11:09:19.203004+00:00 | 53 | false | # Code\n```\nclass Solution {\n fun scoreOfString(s: String) = s.indices.reduce { acc, i -> acc + abs(s[i] - s[i - 1]) }\n}\n``` | 2 | 0 | ['Kotlin'] | 0 |
score-of-a-string | Easy and simple Approach | Beats 99.87% | easy-and-simple-approach-beats-9987-by-k-7pjw | Intuition\nWhen I first saw this problem, I thought about a simple way to calculate the "score" of a string by comparing pairs of characters. The score calculat | kanishakpranjal | NORMAL | 2024-06-01T05:56:39.444712+00:00 | 2024-06-01T05:56:39.444741+00:00 | 6 | false | ## Intuition\nWhen I first saw this problem, I thought about a simple way to calculate the "score" of a string by comparing pairs of characters. The score calculation involves the absolute difference between each pair of characters, and I thought we could step through the string while maintaining a counter for our answer.\n\n## Approach\n1. Initialize two pointers, `i` and `j`, and an accumulator `ans` to store the final score.\n2. Iterate through the string using a loop where `i` runs from the start of the string to the second-last character.\n3. For each character at position `i`, increment the second pointer `j` by one.\n4. Calculate the absolute difference between the characters at positions `i` and `j` and add this difference to `ans`.\n5. Return the accumulated score `ans` after the loop completes.\n\n## Complexity\n- **Time complexity:** \\(O(n)\\)\n - We traverse the string once, making the algorithm linear in relation to the size of the input string.\n- **Space complexity:** \\(O(1)\\)\n - We only use a few integer variables for counting and summing, so the space usage is constant.\n\n## Code\n```java\nclass Solution {\n public int scoreOfString(String s) {\n int j = 0;\n int ans = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n j = i + 1;\n ans += diff(s.charAt(i), s.charAt(j));\n }\n return ans;\n }\n\n int diff(int m, int n) {\n return Math.abs(m - n);\n }\n}\n```\n | 2 | 0 | ['Java'] | 0 |
score-of-a-string | 🔥✅Beat 100%✅|| C/C++/Java/JavaScript/Python || Full explanation✅|| Very easy approach/ Technique✅🔥 | beat-100-ccjavajavascriptpython-full-exp-p830 | Please upvote my solution and give a star if you like the solution...\uD83D\uDE0A\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n | Sachin_Bhawala | NORMAL | 2024-06-01T05:38:57.447331+00:00 | 2024-06-01T05:38:57.447366+00:00 | 58 | false | # Please upvote my solution and give a star if you like the solution...\uD83D\uDE0A\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem "Score of a String" requires us to calculate the total score based on the differences between consecutive characters in the string. The intuition here is to interpret the score as the sum of absolute differences between the ASCII values of each pair of consecutive characters. This allows us to capture the "distance" or "change" between adjacent characters.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialization: Start with a score variable initialized to 0.\n- Iteration: Loop through the string from the first character to the second-last character.\n- Calculation: For each character, calculate the absolute difference between its ASCII value and the ASCII value of the next character.\n- Accumulation: Add this difference to the score.\n- Return Result: After processing all consecutive character pairs, return the score.\n \nThe approach ensures that we efficiently calculate the desired score by leveraging a simple linear scan and difference computation.\n\n# Detailed Steps:\n- Initialize score to 0.\n- Loop through the string using an index i from 0 to s.length() - 2.\n- For each character s[i], compute the absolute difference with s[i + 1].\n- Add this absolute difference to score.\n- After the loop, return the accumulated score.\n\n# Complexity\n- Time complexity: O(n), where n is the length of the string. This is because we iterate through the string exactly once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), as we only use a fixed amount of extra space regardless of the input string size. The space required for the score variable does not scale with the input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C []\nint scoreOfString(char* s) {\n int score = 0;\n for (int i = 0; s[i + 1] != \'\\0\'; i++) {\n score = score + abs(s[i] - s[i + 1]);\n }\n return score;\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int score = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n score = score + abs(int(s[i]) - int(s[i + 1]));\n }\n return score;\n }\n};\n```\n```Java []\npublic int scoreOfString(String s) {\n int score = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n score = score + Math.abs(s.charAt(i) - s.charAt(i + 1));\n }\n return score;\n}\n\n```\n```JavaScript []\nfunction scoreOfString(s) {\n let score = 0;\n for (let i = 0; i < s.length - 1; i++) {\n score = score + Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1));\n }\n return score;\n}\n\n```\n```Python []\ndef scoreOfString(s):\n score = 0\n for i in range(len(s) - 1):\n score += abs(ord(s[i]) - ord(s[i + 1]))\n return score\n\n```\n\n# Conclusion\nThis solution provides an efficient and straightforward method to calculate the score of a string based on the differences between consecutive characters. It operates in linear time, making it suitable for large inputs, and uses constant space, ensuring minimal memory overhead. This clear and efficient approach should be easy to understand and implement, making it an ideal solution for the problem.\n\n\n | 2 | 0 | ['C', 'Python', 'C++', 'Java', 'JavaScript'] | 1 |
score-of-a-string | C++ most optimal solution out there (source: trust me bro) | c-most-optimal-solution-out-there-source-tlpv | \n\n# Intuition\nidk \n\n# Approach\njust loop through one time and uhhh do the math thingy :ppp\n\n# Complexity\n- Time complexity:\nO(n) (because i said so)\n | HMinh | NORMAL | 2024-06-01T05:18:58.436170+00:00 | 2024-06-01T05:36:20.095211+00:00 | 250 | false | \n\n# Intuition\nidk \n\n# Approach\njust loop through one time and uhhh do the math thingy :ppp\n\n# Complexity\n- Time complexity:\nO(n) (because i said so)\n\n- Space complexity:\nO(1); and if it happens to be anything else, nuh uh\n\n# Code\n```\n#define LEETCODE class\n#define BEGIN {\n#define END }\n#define RESTYPE int \n#define SEQ string\n#define SUS 0\n#define DEMENTED for \n#define YEET return\n#define DEF_NOT_ABSOLUTE abs\n#define WALRUS =\n#define LMAO scoreOfString \n#define MMMMOOOOOOAAAAAAAAAAIIIIIIIIIIII public\n#define SOLVE_DEEZ Solution\n#define GETLENMINUS1 .size() - 1\n#define SEMICOLON ;\n#define PLUS +\n#define PLUSPLUS ++\n#define NOTPLUS -\n#define PLUSTIMES +=\n\nLEETCODE SOLVE_DEEZ BEGIN\nMMMMOOOOOOAAAAAAAAAAIIIIIIIIIIII:\n RESTYPE LMAO(SEQ s) BEGIN\n RESTYPE E WALRUS SUS SEMICOLON\n DEMENTED (RESTYPE I BEGIN END SEMICOLON I < s GETLENMINUS1 SEMICOLON I PLUSPLUS)\n E PLUSTIMES DEF_NOT_ABSOLUTE(s[I] NOTPLUS s[I PLUS 1]) SEMICOLON\n YEET E SEMICOLON\n END\nEND SEMICOLON\n``` | 2 | 0 | ['C++'] | 1 |
score-of-a-string | Simple C++ , One liner | simple-c-one-liner-by-mrigaank-ypnm | # Intuition \n\n\n# Approach\n\nSimple approach: subtract adjacent character ASCII values and add them to the count or total.\n\n# Complexity\n- Time complexi | Mrigaank | NORMAL | 2024-06-01T05:05:47.011371+00:00 | 2024-06-01T05:05:47.011409+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. -->\nSimple approach: subtract adjacent character ASCII values and add them to the count or total.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int cnt = 0 ;\n for(int i = 0 ;i < s.size()-1 ; i++){\n int a = abs(int(s[i] - s[i+1]));\n cnt += a;\n }\n return cnt;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
score-of-a-string | 💯 Beats || simple 🐣 || 4 language || Best Formatted 🫰|| | beats-simple-4-language-best-formatted-b-v2kj | \n# Screenshot \uD83C\uDF89 \n\n\n\n---\n\n\n\n# Intuition \uD83D\uDCDA\n\n Given--> One String with\n \n Que description --> (2 <= s.length <= 100)\n | Prakhar-002 | NORMAL | 2024-06-01T04:48:51.541465+00:00 | 2024-06-01T04:48:51.541488+00:00 | 87 | false | \n# Screenshot \uD83C\uDF89 \n\n\n\n---\n\n\n\n# Intuition \uD83D\uDCDA\n\n `Given`--> One String with\n \n `Que description` --> (2 <= s.length <= 100)\n\n we have to score of sum of the absolute difference \n\n between the ASCII values of adjacent characters.\n\n# Approach \uD83D\uDD25\n\n There will be 6 steps \n\n Step 1 -> Make res variable with res = 0\n\n Step 2 -> Apply for loop from 0 to len(nums) - 1 \n\n Step 3 -> sub adjacent means next char from previous one \n\n Step 4 -> add in res \n\n Step 5 -> return res\n\n\n# Complexity \uD83D\uDCAB\n- \u231A Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- \u267B\uFE0F Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code \uD83D\uDC96\n\n```JAVA []\nclass Solution {\n public int scoreOfString(String s) {\n int res = 0;\n\n for (int i = 0; i < s.length() - 1; i++) {\n res += Math.abs(s.charAt(i) - s.charAt(i + 1));\n }\n return res;\n }\n}\n```\n```JAVASCRIPT []\nvar scoreOfString = function (s) {\n let res = 0;\n\n for (let i = 0; i < s.length - 1; i++) {\n res += Math.abs(s.charAt(i).charCodeAt(0) - s.charAt(i + 1).charCodeAt(0));\n }\n return res;\n};\n```\n```PYTHON []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n res = 0\n\n for i in range(len(s) - 1):\n res += abs(ord(s[i]) - ord(s[i + 1]))\n\n return res\n\n```\n``` C []\nint scoreOfString(char* s) {\n int res = 0;\n\n for (int i = 0; i < strlen(s) - 1; i++) {\n res += abs(s[i] - s[i + 1]);\n }\n return res;\n}\n``` | 2 | 0 | ['String', 'C', 'Java', 'Python3', 'JavaScript'] | 0 |
score-of-a-string | Easy JS Solution 🗝️😍💯 | easy-js-solution-by-peermohammad-tdar | 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 | peermohammad | NORMAL | 2024-06-01T03:37:07.510221+00:00 | 2024-06-01T03:37:07.510250+00:00 | 26 | 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```\n/**\n * @param {string} s\n * @return {number}\n */\nvar scoreOfString = function(s) {\n let sum=0\n for(let i=0;i<s.length-1;i++){\n sum=sum+Math.abs([s.charCodeAt(i)]-[s.charCodeAt(i+1)])\n } \n return sum\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
score-of-a-string | Differences of adjacent characters' ASCII values. || Beats 99% users with java & c++ || typescript | differences-of-adjacent-characters-ascii-p1r9 | Approach\nDifferences of adjacent characters\' ASCII values.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Explanation\n1. Initializ | SanketSawant18 | NORMAL | 2024-06-01T03:24:27.234669+00:00 | 2024-06-01T03:24:27.234691+00:00 | 1,142 | false | # Approach\nDifferences of adjacent characters\' ASCII values.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Explanation\n1. **Initialize totalScore:** Start with a variable totalScore set to 0. This will accumulate the sum of the absolute differences.\n\n1. **Loop through the string:** Use a for loop to iterate from the first character to the second last character of the string (i < s.length() - 1).\n\n1. **Compute absolute difference:** For each character at position i, compute the absolute difference between the ASCII values of the character at position i (s.charAt(i)) and the next character (s.charAt(i + 1)). Use Math.abs to get the absolute difference.\n\n1. **Accumulate the score:** Add this difference to totalScore.\nReturn the result: After the loop completes, return the totalScore.\n\n\n---\n\n```java []\nclass Solution {\n public int scoreOfString(String s) {\n int totalScore = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n totalScore += Math.abs(s.charAt(i) - s.charAt(i + 1));\n }\n return totalScore;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(std::string s) {\n int totalScore = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n totalScore += std::abs(s[i] - s[i + 1]);\n }\n return totalScore;\n }\n};\n```\n```python3 []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n total_score = 0\n for i in range(len(s) - 1):\n total_score += abs(ord(s[i]) - ord(s[i + 1]))\n return total_score\n\n```\n```Typescript []\nfunction scoreOfString(s: string): number {\n let totalScore = 0;\n for (let i = 0; i < s.length - 1; i++) {\n totalScore += Math.abs(s.charCodeAt(i) - s.charCodeAt(i + 1));\n }\n return totalScore;\n}\n```\n | 2 | 0 | ['String', 'C++', 'Java', 'TypeScript', 'Python3'] | 1 |
score-of-a-string | Score of a string | score-of-a-string-by-karthick2605-xp27 | Intuition\nThe problem involves calculating the "score" of a string, where the score is defined as the sum of the absolute differences between the ASCII values | KARTHICK2605 | NORMAL | 2024-06-01T02:14:30.896469+00:00 | 2024-06-01T02:14:30.896495+00:00 | 6 | false | # Intuition\nThe problem involves calculating the "score" of a string, where the score is defined as the sum of the absolute differences between the ASCII values of consecutive characters. This essentially measures how "different" adjacent characters are in terms of their ASCII values.\n\n# Approach\n1. **Initialize Score**: Start with a score of 0.\n2. **Iterate Through String**: Loop through the string from the first character to the second-to-last character.\n3. **Calculate Differences**: For each pair of consecutive characters, compute the absolute difference of their ASCII values.\n4. **Update Score**: Add the computed difference to the score.\n5. **Return Final Score**: After the loop, return the final score.\n\n# Complexity\n- **Time complexity**: \\(O(n)\\), where \\(n\\) is the length of the string. We iterate through the string once.\n- **Space complexity**: \\(O(1)\\), as we only use a few extra variables.\n\n# Code\n```java\nclass Solution {\n public int scoreOfString(String s) {\n int score = 0;\n for (int i = 0; i < s.length() - 1; i++) {\n score += Math.abs(s.charAt(i) - s.charAt(i + 1));\n }\n return score;\n }\n}\n```\n\n### Explanation\n1. **Initialize Score**: `int score = 0;` initializes the score to 0.\n2. **Iterate Through String**: The for loop `for (int i = 0; i < s.length() - 1; i++)` iterates through each character in the string except the last one.\n3. **Calculate Differences**: Inside the loop, `Math.abs(s.charAt(i) - s.charAt(i + 1))` calculates the absolute difference between the ASCII values of the current character and the next character.\n4. **Update Score**: The result of the absolute difference is added to `score`.\n5. **Return Final Score**: After the loop completes, the total `score` is returned.\n\nThis approach efficiently calculates the desired score by leveraging the properties of ASCII values and absolute differences, making it straightforward and effective for strings of any length. | 2 | 0 | ['String', 'Java'] | 1 |
score-of-a-string | Straightforward | C++, Python, Java | straightforward-c-python-java-by-not_yl3-7vcl | Approach\n Describe your approach to solving the problem. \nIterate through the string starting from index 1 and sum all the absolute differences (abs(s[i] - s[ | not_yl3 | NORMAL | 2024-06-01T00:07:30.397398+00:00 | 2024-06-01T00:10:09.420506+00:00 | 477 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nIterate through the string starting from index `1` and sum all the absolute differences (`abs(s[i] - s[i-1])`).\n# Code\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum = 0;\n for (int i = 1; i < s.length(); i++)\n sum += abs(s[i] - s[i-1]);\n return sum;\n }\n};\n```\n```python3 []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n return sum(abs(ord(s[i]) - ord(s[i-1])) for i in range(1, len(s)))\n```\n```Java []\nclass Solution {\n public int scoreOfString(String s) {\n int sum = 0;\n for (int i = 1; i < s.length(); i++)\n sum += Math.abs(s.charAt(i) - s.charAt(i-1));\n return sum;\n }\n}\n```\n | 2 | 0 | ['String', 'C', 'Python', 'C++', 'Java', 'Python3'] | 2 |
score-of-a-string | Best and Easiest Explanation || C++ ✅ | best-and-easiest-explanation-c-by-rckroc-ubdh | Intuition\n Describe your first thoughts on how to solve this problem. The problem requires computing a score based on the absolute differences between consecut | rckrockerz | NORMAL | 2024-05-21T13:32:57.574290+00:00 | 2024-05-21T13:32:57.574317+00:00 | 26 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->The problem requires computing a score based on the absolute differences between consecutive characters in a string. This suggests a simple traversal through the string and computing the sum of these differences.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a variable to hold the sum - We will use an integer variable to keep track of the cumulative score.\n2. Traverse the string - Loop through the string starting from the second character to the end.\n3. Compute absolute difference - For each character in the string (from the second to the last), compute the absolute difference between the current character and the previous one\n4. Sum the differences - Add each computed difference to the cumulative sum.\n5. Retum the result - Once the loop completes, the cumulative sum will be the desired score.\n\n# Complexity\n- Time complexity: O(n), where \uD835\uDC5B is the length of the string. This is because we traverse the string once, performing constant-time operations in each iteration.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), since we only use a fixed amount of extra space regardless of the input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum = 0;\n for (int i = 1; i < s.length(); i++)\n sum += abs((s[i - 1] - s[i]));\n return sum;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
score-of-a-string | Swift solution | swift-solution-by-azm819-lv7y | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co | azm819 | NORMAL | 2024-05-05T13:24:48.296023+00:00 | 2024-05-05T13:24:48.296056+00:00 | 114 | false | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n func scoreOfString(_ s: String) -> Int {\n var result = 0\n var firstInd = s.startIndex\n var secondInd = s.index(after: firstInd)\n while secondInd != s.endIndex {\n result += abs(Int(s[firstInd].asciiValue!) - Int(s[secondInd].asciiValue!))\n firstInd = s.index(after: firstInd)\n secondInd = s.index(after: secondInd)\n }\n return result\n }\n}\n\n``` | 2 | 0 | ['String', 'Swift'] | 0 |
score-of-a-string | ✔️✔️✔️very easy solution - for loop - PYTHON || C++ || JAVA - beats 100%⚡⚡⚡ | very-easy-solution-for-loop-python-c-jav-o8qz | Code\nPython []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n fin = 0\n for i in range(len(s) - 1):\n fin += abs(ord( | anish_sule | NORMAL | 2024-04-22T13:55:04.331973+00:00 | 2024-04-22T13:55:04.332015+00:00 | 95 | false | # Code\n```Python []\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n fin = 0\n for i in range(len(s) - 1):\n fin += abs(ord(s[i]) - ord(s[i+1]))\n return fin\n```\n```C++ []\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int fin = 0;\n for(int i = 0; i < s.size() - 1; i++){\n fin += abs(s[i] - s[i+1]);\n }\n return fin;\n }\n};\n```\n```Java []\nclass Solution {\n public int scoreOfString(String s) {\n int fin = 0;\n for(int i = 0; i < s.length() - 1; i++){\n fin += Math.abs(s.charAt(i) - s.charAt(i+1));\n }\n return fin;\n }\n}\n``` | 2 | 0 | ['String', 'C++', 'Java', 'Python3'] | 1 |
score-of-a-string | 👏Beats 99.97% of users with Java | beats-9997-of-users-with-java-by-iamrjb1-26yy | \n# Code\n\nclass Solution {\n public int scoreOfString(String s) {\n int sum=0;\n for(int i=0;i<s.length()-1;i++){\n sum+= Math.abs | iamrjb11 | NORMAL | 2024-04-22T09:46:31.018591+00:00 | 2024-04-22T09:46:31.018620+00:00 | 44 | false | \n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n int sum=0;\n for(int i=0;i<s.length()-1;i++){\n sum+= Math.abs(s.charAt(i)-s.charAt(i+1));\n }\n return sum; \n }\n}\n```\n# Please upvote \uD83D\uDC46 | 2 | 0 | ['Java'] | 0 |
score-of-a-string | Swift💯 | swift-by-upvotethispls-k9u4 | Functional approach (accepted answer)\n\nimport Algorithms\n\nclass Solution {\n func scoreOfString(_ s: String) -> Int {\n s.utf8CString // | UpvoteThisPls | NORMAL | 2024-04-16T20:12:54.750636+00:00 | 2024-06-01T00:47:10.202149+00:00 | 26 | false | **Functional approach (accepted answer)**\n```\nimport Algorithms\n\nclass Solution {\n func scoreOfString(_ s: String) -> Int {\n s.utf8CString // convert `s` into `[CChar]` (`CChar` is typealias for `UInt8`)\n\t\t .dropLast() // drop the zero-terminator that is added to the C string\n\t\t .compactMap(Int.init) // convert all elements from `UInt8` to `Int`\n\t\t .adjacentPairs() // creates a sequence of tuples `[(s[0],s[1]), (s[1],s[2]),...]`\n\t\t .map{abs($0-$1)} // convert tuples to difference `abs(s[x]-s[x+1])`\n\t\t .reduce(0,+) // sum up array of differences\n }\n}\n``` | 2 | 0 | ['Swift'] | 0 |
score-of-a-string | ✅ FP Style | fp-style-by-eleev-j4dm | Solution\n##### #1\n\n`FP` + `.utf8CString` = more performant\n\nswift\nstruct Solution {\n @_optimize(speed)\n func scoreOfString(_ s: String) -> Int {\n | eleev | NORMAL | 2024-04-16T15:43:42.898626+00:00 | 2024-07-25T12:40:42.333592+00:00 | 84 | false | # Solution\n##### #1\n```\n`FP` + `.utf8CString` = more performant\n```\n```swift\nstruct Solution {\n @_optimize(speed)\n func scoreOfString(_ s: String) -> Int {\n let codes = s.utf8CString.dropLast()\n return codes.indices[1...].reduce(0) { score, i in\n score + abs(Int(codes[i] - codes[i - 1]))\n }\n }\n}\n```\n\n##### #2\n```\n`FP` + `.compactMap` = straightforward but less performant\n```\n```swift\nstruct Solution {\n @_optimize(speed)\n func scoreOfString(_ s: String) -> Int {\n let codes = s.compactMap(\\.asciiValue)\n .map(Int.init)\n return codes.indices[1...].reduce(0) { score, i in\n score + abs(codes[i] - codes[i - 1]) \n }\n }\n}\n``` | 2 | 0 | ['String', 'Swift'] | 1 |
score-of-a-string | Ruby one-liner, beats 100%/100% | ruby-one-liner-beats-100100-by-dnnx-f3zb | \n# @param {String} s\n# @return {Integer}\ndef score_of_string(s)\n s.bytes.each_cons(2).sum { (_1 - _2).abs } \nend\n | dnnx | NORMAL | 2024-04-15T18:46:22.673569+00:00 | 2024-04-15T18:46:22.673600+00:00 | 26 | false | ```\n# @param {String} s\n# @return {Integer}\ndef score_of_string(s)\n s.bytes.each_cons(2).sum { (_1 - _2).abs } \nend\n``` | 2 | 0 | ['Ruby'] | 0 |
score-of-a-string | One liner 0ms | one-liner-0ms-by-marktyrkba-fd01 | Code\n\nimpl Solution {\n pub fn score_of_string(s: String) -> i32 {\n s\n .chars()\n .collect::<Vec<_>>()\n .windows(2)\n | marktyrkba | NORMAL | 2024-04-13T18:26:58.497265+00:00 | 2024-04-13T18:26:58.497296+00:00 | 173 | false | # Code\n```\nimpl Solution {\n pub fn score_of_string(s: String) -> i32 {\n s\n .chars()\n .collect::<Vec<_>>()\n .windows(2)\n .map(|w| (w[1] as i32 - w[0] as i32).abs())\n .sum::<i32>()\n }\n}\n``` | 2 | 0 | ['Rust'] | 0 |
score-of-a-string | Simple cpp solution | simple-cpp-solution-by-vaibhav_2077-4j6n | \nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum=0;\n for(int i=0;i<s.size()-1;i++){\n sum+=abs(static_cast<int | vaibhav_2077 | NORMAL | 2024-04-13T16:09:54.889482+00:00 | 2024-04-13T16:09:54.889509+00:00 | 1,148 | false | ```\nclass Solution {\npublic:\n int scoreOfString(string s) {\n int sum=0;\n for(int i=0;i<s.size()-1;i++){\n sum+=abs(static_cast<int>(s[i]) - static_cast<int>(s[i + 1]));\n }\n return sum;\n }\n};``\n``` | 2 | 0 | ['C++'] | 1 |
score-of-a-string | simple solution with 100% beat | simple-solution-with-100-beat-by-vinay_k-fwwi | 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 | vinay_kumar_swami | NORMAL | 2024-04-13T16:07:48.283119+00:00 | 2024-04-13T16:07:48.283152+00:00 | 128 | 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 Solution {\npublic:\n int scoreOfString(string s) {\n vector<int>mp;\n for(int i=0;i<s.size();i++)\n {\n mp.push_back(s[i]);\n }\n int sum=0;\n for(int i=0;i<mp.size()-1;i++)\n {\n sum=sum+abs(mp[i]-mp[i+1]);\n \n }\n return sum;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
score-of-a-string | Beats 100% | counting |Easy Java Solution | beats-100-counting-easy-java-solution-by-205u | \n\n# Code\n\nclass Solution {\n public int scoreOfString(String s) {\n int ans = 0;\n \n for(int i=0;i<s.length()-1;i++){\n | Ikapoor123 | NORMAL | 2024-04-13T16:05:23.952290+00:00 | 2024-04-13T16:05:23.952316+00:00 | 1,995 | false | \n\n# Code\n```\nclass Solution {\n public int scoreOfString(String s) {\n int ans = 0;\n \n for(int i=0;i<s.length()-1;i++){\n ans+=Math.abs(s.charAt(i)-s.charAt(i+1));\n }\n return ans;\n }\n}\n``` | 2 | 0 | ['Array', 'C', 'Python', 'C++', 'Java', 'TypeScript', 'Python3', 'Ruby', 'Kotlin', 'JavaScript'] | 2 |
score-of-a-string | [Python3] One Line - Simple Solution | python3-one-line-simple-solution-by-dolo-ghco | 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 | dolong2110 | NORMAL | 2024-04-13T16:02:27.025831+00:00 | 2024-05-03T03:21:34.937533+00:00 | 55 | 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: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def scoreOfString(self, s: str) -> int:\n return sum(abs(ord(s[i]) - ord(s[i - 1])) for i in range(1, len(s)))\n``` | 2 | 0 | ['String', 'Python3'] | 1 |
score-of-a-string | easy solution | easy-solution-by-haneen_ep-4dto | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | haneen_ep | NORMAL | 2025-04-09T08:46:35.192375+00:00 | 2025-04-09T08:46:35.192375+00:00 | 18 | 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 {number}
*/
var scoreOfString = function (s) {
let res = 0;
for (let i = 1; i < s.length; i++) {
res += Math.abs(s.charCodeAt(i - 1) - s.charCodeAt(i))
}
return res;
};
``` | 1 | 0 | ['JavaScript'] | 0 |
score-of-a-string | 1 ms Beats 99.49% | 41.64 MB Beats 98.46% | 1-ms-beats-9949-4164-mb-beats-9846-by-gu-s7bv | IntuitionThe problem requires calculating the total "score" of a string based on the absolute difference in ASCII values between each pair of adjacent character | gunanshu_joshi | NORMAL | 2025-04-07T03:22:56.829425+00:00 | 2025-04-07T03:22:56.829425+00:00 | 47 | false | # Intuition
The problem requires calculating the total "score" of a string based on the absolute difference in ASCII values between each pair of adjacent characters.
My first thought was to iterate through the string and compute the difference in ASCII values between consecutive characters. Since ASCII values are integers, using `Math.abs()` on their difference gives the required score for each adjacent pair.
---
# Approach
1. Convert the input string into a character array for efficient access.
2. Initialize a variable `ans` to store the cumulative score.
3. Loop through the string starting from the second character.
4. For each character, calculate the absolute difference between it and the previous character using `Math.abs(a[i] - a[i-1])`.
5. Add the result to `ans`.
6. Finally, return `ans` as the total score.
---
# Complexity
- **Time complexity:**
$$O(n)$$
We traverse the string once, where \( n \) is the length of the string.
- **Space complexity:**
$$O(n)$$
Due to the creation of a character array from the string.
---
# Code
```java
class Solution {
public int scoreOfString(String s) {
int ans = 0;
int n = s.length();
char[] a = s.toCharArray();
for (int i = 1; i < n; i++) {
ans += Math.abs(a[i] - a[i - 1]);
}
return ans;
}
}
``` | 1 | 0 | ['Java'] | 0 |
score-of-a-string | 0 ms | Beats 100.00% | Easy and Effective Code | 0-ms-beats-10000-easy-and-effective-code-r7h5 | Code | R_Nirmal_Rajan | NORMAL | 2025-04-06T09:48:00.383981+00:00 | 2025-04-06T09:48:00.383981+00:00 | 76 | false | # Code
```python3 []
class Solution:
def scoreOfString(self, s: str) -> int:
result = 0
for j in range(len(s)):
if j < (len(s)-1):
process = abs(ord(s[j]) - ord(s[j+1]))
result += process
return result
```

| 1 | 0 | ['String', 'Python3'] | 0 |
score-of-a-string | bEAts 100% aNd eASy sOlutioN iN cPp. | beats-100-and-easy-solution-in-cpp-by-xe-nuly | IntuitionApproachComplexity
Time complexity:O(n)
Space complexity:O(1)
Code | xegl87zdzE | NORMAL | 2025-04-02T13:18:11.022177+00:00 | 2025-04-02T13:18:11.022177+00:00 | 50 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int scoreOfString(string s) {
int res=0;
for(int j=1;j<s.size();j++)
{
res=res+abs(s[j]-s[j-1]);
}
return res;
}
};
``` | 1 | 0 | ['String', 'C++'] | 0 |
score-of-a-string | Simple thought... | simple-thought-by-1zkmhmzztg-yvin | IntuitionThe problem requires us to calculate the sum of the absolute differences between the ASCII values of adjacent characters in a string. Since the ASCII v | 1ZkMHmzzTG | NORMAL | 2025-04-01T14:41:51.402776+00:00 | 2025-04-01T14:41:51.402776+00:00 | 52 | false | # Intuition
The problem requires us to calculate the sum of the absolute differences between the ASCII values of adjacent characters in a string. Since the ASCII value of a character can be obtained using ord(), we can iterate through the string, compute these differences, and accumulate the sum.
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
1.Initialize a variable m to store the total score.
2.Determine the length of the string n.
3.Iterate over the string from index 0 to n-2 (so that we always have a valid adjacent character).
4.Compute the absolute difference between the ASCII values of adjacent characters and add it to m.
5.Return the final computed score.
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:$$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def scoreOfString(self, s: str) -> int:
m=0
n=len(s)
for i in range(n-1):
m+=abs(ord(s[i])-ord(s[i+1]))
return m
``` | 1 | 0 | ['Python3'] | 0 |
score-of-a-string | Java Solution Runtime Beats 99.43% Memory Beats 91.84% | java-solution-runtime-beats-9943-memory-ai8ov | ApproachConverting string to CharArray to find char faster by indexComplexity
Time complexity: O(n)
Space complexity: O(n) and still faster:)
Code | yorick_yeng | NORMAL | 2025-03-31T21:47:05.704451+00:00 | 2025-03-31T21:47:05.704451+00:00 | 7 | false | <!-- # Intuition -->
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
Converting string to CharArray to find char faster by index
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$ and still faster:)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int scoreOfString(String s) {
int score = 0;
char[] chars = s.toCharArray();
for (int i = 0, n = chars.length - 1; i < n; i++) {
score += Math.abs(chars[i] - chars[i + 1]);
}
return score;
}
}
``` | 1 | 0 | ['Java'] | 0 |
score-of-a-string | One String Kotlin Solution :) | one-string-kotlin-solution-by-yorick_yen-2cr0 | ApproachGetting the sum of absolute difference between two adjacent charsComplexity
Time complexity: O(n)
Space complexity: O(1)
Code | yorick_yeng | NORMAL | 2025-03-31T21:40:24.068791+00:00 | 2025-03-31T21:40:24.068791+00:00 | 4 | false | <!-- # Intuition -->
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
Getting the sum of absolute difference between two adjacent chars
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```kotlin []
class Solution {
fun scoreOfString(s: String) = (0..<s.lastIndex).sumOf { abs(s[it].code - s[it + 1].code) }
}
``` | 1 | 0 | ['Kotlin'] | 0 |
score-of-a-string | C++ Easy Sol | c-easy-sol-by-maaz_ali27-hnlx | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Maaz_Ali27 | NORMAL | 2025-03-21T11:33:58.818669+00:00 | 2025-03-21T11:33:58.818669+00:00 | 74 | 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:
int scoreOfString(string s) {
int score=0;
for(int i=0; i<s.size()-1; i++){
score += abs(s[i] - s[i+1]); // abs for modulus (converts -ve value to +ve)
}
return score;
}
};
``` | 1 | 0 | ['C++'] | 0 |
score-of-a-string | YOU NEED SOLUTION HUH ? | you-need-solution-huh-by-bruteforceenjoy-ubgw | BRO, HOW IS THIS EVEN CONFUSING ?Code | BruteForceEnjoyer | NORMAL | 2025-03-19T01:47:06.366952+00:00 | 2025-03-19T01:49:40.236972+00:00 | 52 | false | # BRO, HOW IS THIS EVEN CONFUSING ?
# Code
```cpp []
class Solution {
public:
int scoreOfString(string s) {
int res = 0;
for ( int i = 0 ; i < s.size() - 1 ; i ++ ){
res += max(s[i] , s[i+1] ) - min ( s[i] , s[i+1] );
}
return res;
}
};
``` | 1 | 0 | ['String', 'C++'] | 0 |
score-of-a-string | One liner using ord() and sum() in python | one-liner-using-ord-and-sum-in-python-by-6zkk | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | rMSxyPSgWL | NORMAL | 2025-03-18T10:01:32.049828+00:00 | 2025-03-18T10:01:32.049828+00:00 | 56 | 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 scoreOfString(self, s: str) -> int:
return sum(abs(ord(s[x-1])-ord(s[x])) for x in range(1,len(s)))
``` | 1 | 0 | ['Python3'] | 0 |
score-of-a-string | String Score Calculation Using ASCII Differences | string-score-calculation-using-ascii-dif-p8zg | IntuitionThe problem requires calculating a "score" for a given string based on the absolute difference between adjacent character ASCII values. By iterating th | expert07 | NORMAL | 2025-03-06T06:13:29.052246+00:00 | 2025-03-06T06:13:29.052246+00:00 | 100 | false | # Intuition
The problem requires calculating a "score" for a given string based on the absolute difference between adjacent character ASCII values. By iterating through the string and summing these differences, we obtain the final score. This approach efficiently captures variations in character sequences.
# Approach
1. Initialize result to store the sum.
2. Iterate through the string from index 0 to size - 2.
3. For each character pair (s[i], s[i+1]), compute abs(s[i] - s[i+1]) and add it to result.
4. Return the final computed result.
# Complexity
- Time complexity:
O(N), where N is the length of the string. We traverse the string once, performing constant-time operations per character.
- Space complexity:
O(1), as only a few integer variables are used, independent of input size.
# Code
```cpp []
class Solution {
public:
int scoreOfString(string s) {
int result = 0;
for(int i = 0; i < s.size() -1; i++)
{
result = result + abs(s[i] - s[i+1]);
}
return result;
}
};
``` | 1 | 0 | ['Math', 'String', 'Iterator', 'C++'] | 0 |
score-of-a-string | Easy Java Solution | easy-java-solution-by-vermaanshul975-4j7f | IntuitionApproachComplexity
Time complexity: O(N)
Space complexity: O(1)
Code | vermaanshul975 | NORMAL | 2025-03-02T09:04:50.813613+00:00 | 2025-03-02T09:04:50.813613+00:00 | 116 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int scoreOfString(String s) {
int ans = 0;
for(int i = 0;i<s.length()-1;i++){
int abs = Math.abs(((int)s.charAt(i)) - ((int)s.charAt(i+1)));
ans+=abs;
}
return ans;
}
}
``` | 1 | 0 | ['Java'] | 0 |
score-of-a-string | Codegolf-like solution | codegolf-like-solution-by-atiedebee-261x | Not really "code golf" by most peoples standards, but I imagine it looks really strange to people unfamiliar with C.Code | atiedebee | NORMAL | 2025-03-01T17:56:39.980375+00:00 | 2025-03-01T17:56:39.980375+00:00 | 24 | false | Not really "code golf" by most peoples standards, but I imagine it looks really strange to people unfamiliar with C.
# Code
```c []
int scoreOfString(char* s) {
int sum = 0;
while(*++s){
sum += s[-1] > s[0]
? s[-1] - s[0]
: s[0] - s[-1];
}
return sum;
}
``` | 1 | 0 | ['C'] | 0 |
score-of-a-string | C# | c-by-adchoudhary-fhuq | Code | adchoudhary | NORMAL | 2025-02-26T04:11:41.680444+00:00 | 2025-02-26T04:11:41.680444+00:00 | 42 | false | # Code
```csharp []
public class Solution {
public int ScoreOfString(string s) {
int score = 0;
// Iterate over all indices from 0 to the second-to-last index
// Calculate and accumulate the absolute difference of ASCII values
// between adjacent characters
for (int i = 0; i < s.Length - 1; i++) {
score += Math.Abs(s[i] - s[i + 1]);
}
return score;
}
}
``` | 1 | 0 | ['C#'] | 0 |
score-of-a-string | "Easy" C++ Code for Score Of String Beats 100% | easy-c-code-for-score-of-string-beats-10-y9r5 | Intuitioncomapring current and adjacent string character.Approachcomapring current and adjacent string character and subtracting their ASCII values and storing | Sumit22_LC | NORMAL | 2025-02-09T18:29:38.478230+00:00 | 2025-02-09T18:29:38.478230+00:00 | 79 | false | # Intuition
comapring current and adjacent string character.
# Approach
comapring current and adjacent string character and subtracting their ASCII values and storing them into a variable and returning it.
# Complexity
- Time complexity: O(n)
- Space complexity: O(1)
# Code
```cpp []
class Solution {
public:
int scoreOfString(string s) {
int score=0;
for(int i=0;i<s.size()-1;i++){
score=score+abs(s[i+1]-s[i]);
}
return score;
}
};
``` | 1 | 0 | ['C++'] | 1 |
score-of-a-string | Here's The Solution in Java | heres-the-solution-in-java-by-harishkann-caxg | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | harishkannan05 | NORMAL | 2025-01-28T10:12:06.745134+00:00 | 2025-01-28T10:12:06.745134+00:00 | 136 | 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 int scoreOfString(String s) {
int score = 0;
for (int i = 0; i < s.length() - 1; i++) {
score += Math.abs(s.charAt(i) - s.charAt(i + 1));
}
return score;
}
}
``` | 1 | 0 | ['Java'] | 0 |
score-of-a-string | Solution for Score of a String | solution-for-score-of-a-string-by-abhina-zg18 | IntuitionI thought about creating an array and storing all the ascii values of the characters and then using them to evaluate the score.ApproachI did the questi | AbhinavGupta012 | NORMAL | 2025-01-27T08:52:58.477448+00:00 | 2025-01-27T08:52:58.477448+00:00 | 64 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
I thought about creating an array and storing all the ascii values of the characters and then using them to evaluate the score.
# Approach
<!-- Describe your approach to solving the problem. -->
I did the question using Brute-Force Approach.
First we create an array to store all the ascii values of each character in the string "s".
After that all that we would need is to calculate the score with the given method:
```.
Sum of Absolute Difference between Adjacent characters
```
# 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 int scoreOfString(String s) {
int[] arr = new int[s.length()];
int score = 0;
for (int i = 0; i < s.length(); i++){
arr[i] = s.charAt(i);
}
for (int i = 0; i < arr.length - 1; i++){
if (arr[i] - arr[i + 1] < 0){
score += arr[i + 1] - arr[i];
}
else{
score += arr[i] - arr[i + 1];
}
}
return score;
}
}
``` | 1 | 0 | ['Java'] | 0 |
score-of-a-string | simple solution | simple-solution-by-lathika17-sqpn | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | lathika17 | NORMAL | 2025-01-19T10:49:52.418596+00:00 | 2025-01-19T10:49:52.418596+00:00 | 51 | 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 {number}
*/
var scoreOfString = function(s) {
let x = 0;
for (let i = 1; i < s.length; i++) {
x += Math.abs(s.charCodeAt(i - 1) - s.charCodeAt(i));
}
return x;
};
``` | 1 | 0 | ['JavaScript'] | 0 |
score-of-a-string | last submission beat 100% of other submissions' runtime || easy and simplle approach || o(n)||c++|| | last-submission-beat-100-of-other-submis-gonh | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Rohan07_6473 | NORMAL | 2025-01-16T17:35:52.771960+00:00 | 2025-01-16T17:35:52.771960+00:00 | 74 | 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:
int scoreOfString(string s) {
int n = s.size();
if(n<2) return 0;
int sum =0;
for(int i =0 ;i<n-1 ;i++){
sum+=abs(s[i] - s[i+1]);
}
return sum;
}
};
``` | 1 | 0 | ['C++'] | 0 |
score-of-a-string | Single line solution || Python || Super fast, beats 100% in run time || Easy solution | single-line-solution-python-super-fast-b-0g40 | Code | sheshan25 | NORMAL | 2025-01-15T20:37:54.264755+00:00 | 2025-01-15T20:37:54.264755+00:00 | 90 | false |
# Code
```python3 []
class Solution:
def scoreOfString(self, s: str) -> int:
return sum(abs(ord(s[i-1]) - ord(s[i])) for i in range(1, len(s)))
``` | 1 | 0 | ['Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.