Last updated on January 5th, 2025 at 01:19 am
Here, we see Arithmetic Slices LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Dynamic Programming, Math
Companies
Baidu
Level of Question
Medium
![Arithmetic Slices LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Arithmetic Slices LeetCode Solution
Table of Contents
1. Problem Statement
An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
- For example,
[1,3,5,7,9]
,[7,7,7,7]
, and[3,-1,-5,-9]
are arithmetic sequences.
Given an integer array nums
, return the number of arithmetic subarrays of nums
.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [1,2,3,4]
Output: 3
Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.
Example 2:
Input: nums = [1]
Output: 0
2. Coding Pattern Used in Solution
The coding pattern used in this code is Dynamic Programming. The problem involves breaking down the solution into smaller subproblems (checking if a sequence is arithmetic) and using previously computed results to build the final solution. Specifically, the code uses a bottom-up dynamic programming approach to count the number of arithmetic slices in the array.
3. Code Implementation in Different Languages
3.1 Arithmetic Slices C++
class Solution { public: int numberOfArithmeticSlices(vector<int>& nums) { int count=0,ans=0; for(int i=2;i<nums.size();i++) { if(nums[i]-nums[i-1]==nums[i-1]-nums[i-2]){ count++; ans+=count;} else count=0; } return ans; } };
3.2 Arithmetic Slices Java
class Solution { public int numberOfArithmeticSlices(int[] nums) { var slices = 0; for (int i = 2, prev = 0; i < nums.length; i++) slices += (nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]) ? ++prev : (prev = 0); return slices; } }
3.3 Arithmetic Slices JavaScript
var numberOfArithmeticSlices = function(nums) { let sum = 0, dp = Array(nums.length).fill(0); for (var i = 2; i <= dp.length - 1; i++) { if (nums[i] - nums[i - 1] === nums[i - 1] - nums[i - 2]) { dp[i] = 1 + dp[i - 1]; sum += dp[i]; } } return sum; };
3.4 Arithmetic Slices Python
class Solution(object): def numberOfArithmeticSlices(self, nums): le=len(nums) l=[0]*(le) for i in range(2,le): if nums[i]-nums[i-1] == nums[i-1]-nums[i-2]: l[i]=1+l[i-1] return sum(l)
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n) | O(1) |
Java | O(n) | O(1) |
JavaScript | O(n) | O(n) |
Python | O(n) | O(n) |