Design a Stack With Increment Operation
1381. Design a Stack With Increment Operation
Difficulty: Medium
Topics: Array, Stack, Design
Design a stack that supports increment operations on its elements.
Implement the CustomStack class:
- CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack.
- void push(int x) Adds x to the top of the stack if the stack has not reached the maxSize.
- int pop() Pops and returns the top of the stack or -1 if the stack is empty.
- void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, increment all the elements in the stack.
Example 1:
- Input:
["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"] [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
- Output:
[null,null,null,2,null,null,null,null,null,103,202,201,-1]
- Explanation:
CustomStack stk = new CustomStack(3); // Stack is Empty [] stk.push(1); // stack becomes [1] stk.push(2); // stack becomes [1, 2] stk.pop(); // return 2 --> Return top of the stack 2, stack becomes [1] stk.push(2); // stack becomes [1, 2] stk.push(3); // stack becomes [1, 2, 3] stk.push(4); // stack still [1, 2, 3], Do not add another elements as size is 4 stk.increment(5, 100); // stack becomes [101, 102, 103] stk.increment(2, 100); // stack becomes [201, 202, 103] stk.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202] stk.pop(); // return 202 --> Return top of the stack 202, stack becomes [201] stk.pop(); // return 201 --> Return top of the stack 201, stack becomes [] stk.pop(); // return -1 --> Stack is empty return -1.
Constraints:
- 1 <= maxSize, x, k <= 1000
- 0 <= val <= 100
- At most 1000 calls will be made to each method of increment, push and pop each separately.
Hint:
- Use an array to represent the stack. Push will add new integer to the array. Pop removes the last element in the array and increment will add val to the first k elements of the array.
- This solution run in O(1) per push and pop and O(k) per increment.
Solution:
We can follow a typical stack implementation but with an additional method that allows incrementing the bottom k elements by a given value. The increment operation will iterate through the first k elements of the stack and add the value to each.
We'll implement this stack in PHP 5.6, using an array to represent the stack. The core operations are:
- push(x): Adds the element x to the top of the stack, if the stack has not reached its maxSize.
- pop(): Removes the top element of the stack and returns it. If the stack is empty, return -1.
- increment(k, val): Adds the value val to the first k elements in the stack, or to all the elements if the stack contains fewer than k elements.
Let's implement this solution in PHP: 1381. Design a Stack With Increment Operation
<?php class CustomStack { /** * @var array */ private $stack; /** * @var int */ private $maxSize; /** * Constructor to initialize the stack with a given maxSize * * @param Integer $maxSize */ function __construct($maxSize) { ... ... ... /** * go to ./solution.php */ } /** * Push an element to the stack if it has not reached the maxSize * * @param Integer $x * @return NULL */ function push($x) { ... ... ... /** * go to ./solution.php */ } /** * Pop the top element from the stack and return it, return -1 if the stack is empty * * @return Integer */ function pop() { ... ... ... /** * go to ./solution.php */ } /** * Increment the bottom k elements of the stack by val * * @param Integer $k * @param Integer $val * @return NULL */ function increment($k, $val) { ... ... ... /** * go to ./solution.php */ } } /** * Your CustomStack object will be instantiated and called as such: * $obj = CustomStack($maxSize); * $obj->push($x); * $ret_2 = $obj->pop(); * $obj->increment($k, $val); */ // Example usage $customStack = new CustomStack(3); // Stack is Empty [] $customStack->push(1); // stack becomes [1] $customStack->push(2); // stack becomes [1, 2] echo $customStack->pop() . "\n"; // return 2, stack becomes [1] $customStack->push(2); // stack becomes [1, 2] $customStack->push(3); // stack becomes [1, 2, 3] $customStack->push(4); // stack still [1, 2, 3], maxSize is 3 $customStack->increment(5, 100); // stack becomes [101, 102, 103] $customStack->increment(2, 100); // stack becomes [201, 202, 103] echo $customStack->pop() . "\n"; // return 103, stack becomes [201, 202] echo $customStack->pop() . "\n"; // return 202, stack becomes [201] echo $customStack->pop() . "\n"; // return 201, stack becomes [] echo $customStack->pop() . "\n"; // return -1, stack is empty ?> <h3> Explanation: </h3> <ol> <li> <p><strong>push($x)</strong>:</p> <ul> <li>We use array_push to add elements to the stack. We check if the current size of the stack is less than maxSize. If it is, we push the new element.</li> </ul> </li> <li> <p><strong>pop()</strong>:</p> <ul> <li>We check if the stack is empty using empty($this->stack). If it's not empty, we pop the top element using array_pop and return it. If it's empty, we return -1.</li> </ul> </li> <li> <p><strong>increment($k, $val)</strong>:</p> <ul> <li>We calculate the minimum of k and the current stack size to determine how many elements to increment. We then loop over these elements, adding val to each.</li> </ul> </li> </ol> <h3> Example Execution: </h3> <p>For the input operations:<br> </p> <pre class="brush:php;toolbar:false">["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"] [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
The output will be:
[null, null, null, 2, null, null, null, null, null, 103, 202, 201, -1]
This output is based on the following:
- push(1): Stack becomes [1]
- push(2): Stack becomes [1, 2]
- pop(): Returns 2, stack becomes [1]
- push(2): Stack becomes [1, 2]
- push(3): Stack becomes [1, 2, 3]
- push(4): Stack remains [1, 2, 3] (maxSize reached)
- increment(5, 100): Stack becomes [101, 102, 103]
- increment(2, 100): Stack becomes [201, 202, 103]
- pop(): Returns 103, stack becomes [201, 202]
- pop(): Returns 202, stack becomes [201]
- pop(): Returns 201, stack becomes []
- pop(): Returns -1 (stack is empty)
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
- GitHub
The above is the detailed content of Design a Stack With Increment Operation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.
