Swift Coding Test Course, Calculate the Sum of Remainders

Recently, the importance of algorithm coding tests in the field of software development has been growing. This is because many companies evaluate candidates’ problem-solving abilities through coding tests during the interview process. In this article, we will solve the ‘Subarray Sum Remainder’ problem using the Swift language, covering everything from understanding the problem to the overall resolution process.

Problem Description

Given an integer array nums and an integer k, write a function to calculate the remainder of the sum of all subarrays of nums when divided by k, and return the total sum of these remainders.

Example Problem

  • Input: nums = [1, 2, 3, 4, 5], k = 3
  • Output: 10
  • Description: The sums of the subarrays are 1, 1+2=3, 1+2+3=6, 1+2+3+4=10, ..., and we need to find the remainders of each when divided by 3.

Approach to the Problem

To solve this problem, we first need to generate all subarrays, calculate their sums, and then find the remainder when divided by k. However, generating all subarrays directly can lead to a time complexity of more than O(n^3), so a more efficient approach is needed.

We can accumulate the sums of the subarrays and use this to solve the problem. In this process, we can think about how to store the remainders.

Swift Implementation


func subarraySumRemainder(nums: [Int], k: Int) -> Int {
    var totalRemainderSum = 0
    let n = nums.count
    
    for start in 0..<n {="" var="" currentsum="0" for="" end="" in="" start..<n="" +="nums[end]" totalremaindersum="" %="" k="" }="" return="" }<="" code=""></n>
<h2>Code Explanation</h2> <p>The above function <code>subarraySumRemainder</code> takes <code>nums</code> and <code>k</code> as inputs and calculates the sum of remainders.</p> <ul> <li><code>totalRemainderSum</code>: A variable that stores the sum of all subarray remainders.</li> <li><code>n</code>: Stores the size of the array.</li> <li><code>for start in 0..<n< code="">: Sets the starting index for each subarray.</n<></code></li><code> <li><code>currentSum</code>: A variable that stores the sum of the current subarray.</li> <li><code>for end in start..<n< code="">: Sets the ending index for the subarray and updates the current sum.</n<></code></li><code> <li><code>totalRemainderSum += currentSum % k</code>: Calculates the remainder and adds it to the total sum.</li> </code></code></ul><code><code> <h2>Time Complexity Analysis</h2> <p>The time complexity of this algorithm is <code>O(n^2)</code>. This is because, in the worst case, we need to traverse all subarrays of the array. Since calculating the remainder can be done in constant time, the total complexity is determined by the time spent generating the subarrays.</p> <h2>Other Approaches</h2> <p>This problem can be solved in various ways. For example, using the prefix sum technique can provide better time complexity. By using prefix sums, we can quickly find the sum over a specific range, thus reducing the time required to calculate the remainder.</p> <h3>Method Using Prefix Sum</h3> <pre><code> func subarraySumRemainderUsingPrefixSum(nums: [Int], k: Int) -&gt; Int { var prefixSums = [Int](repeating: 0, count: nums.count + 1) for i in 1...nums.count { prefixSums[i] = prefixSums[i - 1] + nums[i - 1] } var totalRemainderSum = 0 for start in 0..<nums.count {="" for="" end="" in="" start="" +="" 1...nums.count="" let="" currsum="prefixSums[end]" -="" prefixsums[start]="" totalremaindersum="" %="" k="" }="" return="" }<="" code=""></nums.count></code></pre><code> <h2>Conclusion</h2> <p>In this article, we explored the method of solving the 'Subarray Sum Remainder' problem using the Swift language. We provided a comprehensive explanation from understanding the problem and approach to implementation and time complexity analysis. There are multiple approaches to algorithm problems, and they require creative thinking to solve. I hope you continue to develop your coding skills through consistent practice.</p> <h2>References</h2> <ul> <li>LeetCode (https://leetcode.com)</li> <li>GeeksforGeeks (https://www.geeksforgeeks.org)</li> <li>Algorithm Visualizer (https://algorithm-visualizer.org)</li> </ul> </code></code></code>
<code><code> <div id="jp-relatedposts" class="jp-relatedposts"> <h3 class="jp-relatedposts-headline"><em>관련</em></h3> </div> </code></code>
<code><code> <footer class="entry-footer"> <span class="byline"><span class="author vcard"><img alt="" src="https://secure.gravatar.com/avatar/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=49&amp;d=mm&amp;r=g" srcset="https://secure.gravatar.com/avatar/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=98&amp;d=mm&amp;r=g 2x" class="avatar avatar-49 photo" height="49" width="49" decoding="async"><span class="screen-reader-text">Author </span> <a class="url fn n" href="https://atmokpo.com/w/en/author/root/">root</a></span></span><span class="posted-on"><span class="screen-reader-text">Posted on </span><a href="https://atmokpo.com/w/34700/" rel="bookmark"><time class="entry-date published" datetime="2024-11-01T09:31:01+00:00">2024/11/01</time><time class="updated" datetime="2024-11-01T11:26:55+00:00">2024/11/01</time></a></span><span class="cat-links"><span class="screen-reader-text">Categories </span><a href="https://atmokpo.com/w/category/swift-coding-test/" rel="category tag">Swift Coding Test</a></span> </footer><!-- .entry-footer --> </code></code>
<code><code> <nav class="navigation post-navigation" aria-label="Posts"> <h2 class="screen-reader-text">Post navigation</h2> <div class="nav-links"><div class="nav-previous"><a href="https://atmokpo.com/w/34698/" rel="prev"><span class="meta-nav" aria-hidden="true">Previous</span> <span class="screen-reader-text">Previous post:</span> <span class="post-title">Swift Coding Test Course, Depth First Search</span></a></div><div class="nav-next"><a href="https://atmokpo.com/w/34702/" rel="next"><span class="meta-nav" aria-hidden="true">Next</span> <span class="screen-reader-text">Next post:</span> <span class="post-title">Swift Coding Test Course, Sorting Digits in Descending Order</span></a></div></div> </nav> </code></code>
<code><code> </code></code>
<code><code> <aside id="secondary" class="sidebar widget-area"> <section id="block-2" class="widget widget_block widget_search"><form role="search" method="get" action="https://atmokpo.com/w/en/" class="wp-block-search__button-outside wp-block-search__text-button wp-block-search"><label class="wp-block-search__label" for="wp-block-search__input-1">Search</label><div class="wp-block-search__inside-wrapper "><input class="wp-block-search__input" id="wp-block-search__input-1" placeholder="" value="" type="search" name="s" required=""><button aria-label="Search" class="wp-block-search__button wp-element-button" type="submit">Search</button></div></form></section><section id="block-10" class="widget widget_block"><ul class="wp-block-page-list"><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/c-coding-test-tutorials/">C++ Coding Test Tutorials</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/collection-of-c-coding-test-tutorials/">Collection of C# Coding Test Tutorials</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/deep-learning-automated-trading/">Deep learning Automated trading</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/deep-learning-natural-language-processing/">Deep learning natural language processing</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/english-sentence-study/">English sentence study</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/flutter-course/">Flutter course</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/gan-deep-learning-course/">GAN deep learning course</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/java-android-app-development/">Java Android app development</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/java-coding-test/">Java Coding Test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/javascript-coding-test/">Javascript Coding Test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/kotlin-android-app-development/">Kotlin Android app development</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/kotlin-coding-test/">Kotlin coding test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/python-auto-trading/">Python Auto Trading</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/python-coding-test/">Python Coding Test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/python-study/">Python Study</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/pytorch-study/">PyTorch Study</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/react-basics-course/">React basics course</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/spring-boot-backend-development/">Spring Boot backend development</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/swift-coding-test/">Swift Coding Test</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/swift-iphone-app-development-swiftui/">Swift iPhone app development (SwiftUI)</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/swift-iphone-app-development-uikit/">Swift iPhone app development (UIKit)</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/unity-basic/">Unity Basic</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/using-hugging-face/">Using Hugging Face</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/uwp-programming/">UWP Programming</a></li><li class="wp-block-pages-list__item"><a class="wp-block-pages-list__item__link" href="https://atmokpo.com/w/wpf-programming/">WPF Programming</a></li></ul></section><section id="listcategorypostswidget-3" class="widget widget_listcategorypostswidget"><h2 class="widget-title">Category Post List</h2><ul class="lcp_catlist" id="lcp_instance_listcategorypostswidget-3"><li><a href="https://atmokpo.com/w/34736/">Swift Coding Test Course, Bubble Sort</a></li><li><a href="https://atmokpo.com/w/34734/">Swift Coding Test Course, Bubble Sort Program 2</a></li><li><a href="https://atmokpo.com/w/34732/">Swift Coding Test Course, Bubble Sort Program 1</a></li><li><a href="https://atmokpo.com/w/34730/">Swift Coding Test Course, Finding the Kth Number in an Array</a></li><li><a href="https://atmokpo.com/w/34728/">Swift Coding Test Course, Arrays and Lists</a></li><li><a href="https://atmokpo.com/w/34724/">Swift Coding Test Course, Calculating the Amount of Water</a></li><li><a href="https://atmokpo.com/w/34726/">Swift Coding Test Course, Exploring a Maze</a></li><li><a href="https://atmokpo.com/w/34722/">Swift Coding Test Course, String Search</a></li><li><a href="https://atmokpo.com/w/34720/">Swift Coding Test Course, Counting Leaf Nodes</a></li><li><a href="https://atmokpo.com/w/34718/">Swift Coding Test Course, Why is Debugging Important?</a></li></ul><ul class="lcp_paginator"><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=9#lcp_instance_listcategorypostswidget-3" title="9" class="lcp_prevlink">&lt;&lt;</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=1#lcp_instance_listcategorypostswidget-3" title="1">1</a></li><span class="lcp_elipsis">...</span><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=5#lcp_instance_listcategorypostswidget-3" title="5">5</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=6#lcp_instance_listcategorypostswidget-3" title="6">6</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=7#lcp_instance_listcategorypostswidget-3" title="7">7</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=8#lcp_instance_listcategorypostswidget-3" title="8">8</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=9#lcp_instance_listcategorypostswidget-3" title="9">9</a></li><li class="lcp_currentpage">10</li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=11#lcp_instance_listcategorypostswidget-3" title="11">11</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=12#lcp_instance_listcategorypostswidget-3" title="12">12</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=13#lcp_instance_listcategorypostswidget-3" title="13">13</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=14#lcp_instance_listcategorypostswidget-3" title="14">14</a></li><li><a href="https://atmokpo.com/w/34700/?lcp_pagelistcategorypostswidget-3=11#lcp_instance_listcategorypostswidget-3" title="11" class="lcp_nextlink">&gt;&gt;</a></li></ul></section><section id="block-3" class="widget widget_block"> <div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow"> <h3 class="wp-block-heading">최신 글</h3> <ul class="wp-block-latest-posts__list wp-block-latest-posts"><li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37979/">Unity 2D Game Development, Create a Platform Game Including Jumps, Obstacles, and Enemies.</a></li> <li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37977/">Unity 2D Game Development, Adding Effects Using Particle System Implementing visual effects such as explosions and flames using the particle system.</a></li> <li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37973/">Unity 2D Game Development, Touch Input and Mobile Game Development Creation of 2D games utilizing touch input on mobile devices.</a></li> <li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37975/">Unity 2D Game Development, Power-Up and Buff System Creating a power-up system that temporarily enhances the player’s abilities.</a></li> <li><a class="wp-block-latest-posts__post-title" href="https://atmokpo.com/w/37971/">Unity 2D Game Development, Quest and Mission System Creating a quest system where rewards are given for achieving specific goals.</a></li> </ul></div></div> </section> </aside><!-- .sidebar .widget-area --> </code></code>
<code><code> <footer id="colophon" class="site-footer"> <div class="site-info"> <span class="site-title"><a href="https://atmokpo.com/w/en/" rel="home">라이브스마트</a></span> <a href="https://wordpress.org/" class="imprint"> Proudly powered by WordPress </a> </div><!-- .site-info --> </footer><!-- .site-footer --> </code></code>
<code><code> </code></code>
<code><code> <script type="speculationrules"> {"prefetch":[{"source":"document","where":{"and":[{"href_matches":"\/w\/*"},{"not":{"href_matches":["\/w\/wp-*.php","\/w\/wp-admin\/*","\/w\/wp-content\/uploads\/*","\/w\/wp-content\/*","\/w\/wp-content\/plugins\/*","\/w\/wp-content\/themes\/twentysixteen\/*","\/w\/*\\?(.+)"]}},{"not":{"selector_matches":"a[rel~=\"nofollow\"]"}},{"not":{"selector_matches":".no-prefetch, .no-prefetch a"}}]},"eagerness":"conservative"}]} </script> <link rel="stylesheet" id="lcp_paginator-css" href="https://atmokpo.com/w/wp-content/plugins/list-category-posts//lcp_paginator.css?ver=6.8" media="all"> <script src="https://atmokpo.com/w/wp-content/plugins/collapse-magic/js/collapse-magic.js?x=60&amp;ver=1.0" id="claps-main-js"></script> <script defer="" src="https://atmokpo.com/w/wp-content/plugins/koko-analytics/assets/dist/js/script.js?ver=1.6.4" id="koko-analytics-js"></script> <script src="https://atmokpo.com/w/wp-content/plugins/responsive-accordion-and-collapse/js/accordion-custom.js?ver=6.8" id="call_ac-custom-js-front-js"></script> <script src="https://atmokpo.com/w/wp-content/plugins/responsive-accordion-and-collapse/js/accordion.js?ver=6.8" id="call_ac-js-front-js"></script> <script src="https://stats.wp.com/e-202516.js" id="jetpack-stats-js" data-wp-strategy="defer"></script> <script id="jetpack-stats-js-after"> _stq = window._stq || []; _stq.push([ "view", JSON.parse("{\"v\":\"ext\",\"blog\":\"238449126\",\"post\":\"34700\",\"tz\":\"0\",\"srv\":\"atmokpo.com\",\"j\":\"1:14.2.1\"}") ]); _stq.push([ "clickTrackerInit", "238449126", "34700" ]); </script> <script> document.querySelectorAll("code").forEach(function(codeBlock) { // 내용에 '<'나 '>'가 포함된 경우에만 변환 if (codeBlock.innerHTML.includes("<") && codeBlock.innerHTML.includes(">")) { codeBlock.textContent = codeBlock.innerHTML; } }); </script></code></code>