{"id":33398,"date":"2024-11-01T09:16:08","date_gmt":"2024-11-01T09:16:08","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=33398"},"modified":"2024-11-01T11:38:52","modified_gmt":"2024-11-01T11:38:52","slug":"java-coding-test-course-segment-tree","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/33398\/","title":{"rendered":"Java Coding Test Course, Segment Tree"},"content":{"rendered":"<p><body><\/p>\n<p>Hello! In this article, we will learn about the <strong>Segment Tree<\/strong>, which is one of the algorithms that can be useful in coding tests using Java. The segment tree is primarily used to efficiently handle range queries and range updates. In this article, I will explain the basic concept of segment trees, example problems related to it, and the detailed process of solving those problems.<\/p>\n<h2>What is a Segment Tree?<\/h2>\n<p>A segment tree is a data structure used to store information about a specific range in an array and to process queries efficiently. It mainly supports the following operations:<\/p>\n<ul>\n<li>Calculating the sum of a specified range<\/li>\n<li>Updating the value at a specified position<\/li>\n<li>Finding the minimum and maximum values in a range<\/li>\n<\/ul>\n<p>A segment tree can process queries in O(log n) time with a space complexity of O(n). This allows for effective handling of large-scale data.<\/p>\n<h2>Problem Introduction<\/h2>\n<p>Now, let&#8217;s solve a problem using the &#8216;Segment Tree.&#8217;<\/p>\n<h3>Problem Description<\/h3>\n<p>Given an array of integers, write a program that provides two functions: to find the sum of a specific range and to update the value at a specific index.<\/p>\n<p>The functionalities to be implemented are as follows:<\/p>\n<ol>\n<li>Range Sum Query: Given two indices <code>l<\/code> and <code>r<\/code>, return the sum between <code>l<\/code> and <code>r<\/code>.<\/li>\n<li>Update Query: Update the value at index <code>index<\/code> to <code>value<\/code>.<\/li>\n<\/ol>\n<h3>Input Format<\/h3>\n<pre>\nFirst line: size of the array n (1 \u2264 n \u2264 10^5)\nSecond line: n integers (1 \u2264 arr[i] \u2264 10^9)\nThird line: number of queries q\nNext q lines: the queries are one of two formats:\n    1. 1 l r (range sum query)\n    2. 2 index value (update query)\n<\/pre>\n<h3>Output Format<\/h3>\n<pre>\nOutput the results of the range sum queries line by line.\n<\/pre>\n<h2>Problem Solving Process<\/h2>\n<h3>1. Implementing the Segment Tree<\/h3>\n<p>First, we need to implement the segment tree. The segment tree is structured to store the sums from non-leaf nodes down to the leaf nodes. We will declare an array <code>tree<\/code> for this purpose and write a method to build the tree.<\/p>\n<pre><code>java\npublic class SegmentTree {\n    private int[] tree;\n    private int n;\n\n    public SegmentTree(int[] arr) {\n        n = arr.length;\n        tree = new int[n * 4];\n        buildTree(arr, 0, 0, n - 1);\n    }\n\n    private void buildTree(int[] arr, int node, int start, int end) {\n        if (start == end) {\n            tree[node] = arr[start];\n        } else {\n            int mid = (start + end) \/ 2;\n            buildTree(arr, node * 2 + 1, start, mid);\n            buildTree(arr, node * 2 + 2, mid + 1, end);\n            tree[node] = tree[node * 2 + 1] + tree[node * 2 + 2];\n        }\n    }\n\n    \/\/ Range sum query method\n    public int rangeSum(int l, int r) {\n        return rangeSumHelper(0, 0, n - 1, l, r);\n    }\n\n    private int rangeSumHelper(int node, int start, int end, int l, int r) {\n        if (r < start || end < l) {\n            return 0; \/\/ Query range does not overlap with node range\n        }\n        if (l <= start &#038;&#038; end <= r) {\n            return tree[node]; \/\/ Node range is completely within query range\n        }\n        int mid = (start + end) \/ 2;\n        int leftSum = rangeSumHelper(node * 2 + 1, start, mid, l, r);\n        int rightSum = rangeSumHelper(node * 2 + 2, mid + 1, end, l, r);\n        return leftSum + rightSum;\n    }\n\n    \/\/ Update method\n    public void update(int index, int value) {\n        updateHelper(0, 0, n - 1, index, value);\n    }\n\n    private void updateHelper(int node, int start, int end, int index, int value) {\n        if (start == end) {\n            tree[node] = value;\n        } else {\n            int mid = (start + end) \/ 2;\n            if (start <= index &#038;&#038; index <= mid) {\n                updateHelper(node * 2 + 1, start, mid, index, value);\n            } else {\n                updateHelper(node * 2 + 2, mid + 1, end, index, value);\n            }\n            tree[node] = tree[node * 2 + 1] + tree[node * 2 + 2];\n        }\n    }\n}\n<\/code><\/pre>\n<h3>2. Main Program<\/h3>\n<p>Now, I will write the main program that includes the segment tree class to handle input and process queries.<\/p>\n<pre><code>java\nimport java.util.Scanner;\n\npublic class Main {\n    public static void main(String[] args) {\n        Scanner scanner = new Scanner(System.in);\n        \n        int n = scanner.nextInt();\n        int[] arr = new int[n];\n        \n        for (int i = 0; i < n; i++) {\n            arr[i] = scanner.nextInt();\n        }\n\n        SegmentTree segmentTree = new SegmentTree(arr);\n        \n        int q = scanner.nextInt();\n        for (int i = 0; i < q; i++) {\n            int type = scanner.nextInt();\n            if (type == 1) { \/\/ Range sum query\n                int l = scanner.nextInt();\n                int r = scanner.nextInt();\n                System.out.println(segmentTree.rangeSum(l, r));\n            } else if (type == 2) { \/\/ Update query\n                int index = scanner.nextInt();\n                int value = scanner.nextInt();\n                segmentTree.update(index, value);\n            }\n        }\n        \n        scanner.close();\n    }\n}\n<\/code><\/pre>\n<h2>3. Time Complexity Analysis<\/h2>\n<p>The time complexity of the segment tree is as follows:<\/p>\n<ul>\n<li>Range sum query: O(log n)<\/li>\n<li>Update query: O(log n)<\/li>\n<\/ul>\n<p>Therefore, processing q queries with an array containing n data results in an overall time complexity of O(q log n).<\/p>\n<h2>Conclusion<\/h2>\n<p>In this tutorial, we learned about segment trees in detail. The segment tree is a powerful tool that can efficiently solve various problems and can be used in multiple fields, such as counting problems, maximum\/minimum problems, etc. I hope this material helps you in your coding test preparation! If you have any additional questions, please leave a comment.<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello! In this article, we will learn about the Segment Tree, which is one of the algorithms that can be useful in coding tests using Java. The segment tree is primarily used to efficiently handle range queries and range updates. In this article, I will explain the basic concept of segment trees, example problems related &hellip; <a href=\"https:\/\/atmokpo.com\/w\/33398\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Java Coding Test Course, Segment Tree&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[139],"tags":[],"class_list":["post-33398","post","type-post","status-publish","format-standard","hentry","category-java-coding-test"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Java Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/33398\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Hello! In this article, we will learn about the Segment Tree, which is one of the algorithms that can be useful in coding tests using Java. The segment tree is primarily used to efficiently handle range queries and range updates. In this article, I will explain the basic concept of segment trees, example problems related &hellip; \ub354 \ubcf4\uae30 &quot;Java Coding Test Course, Segment Tree&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/33398\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:16:08+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:38:52+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"2\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/33398\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33398\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Java Coding Test Course, Segment Tree\",\"datePublished\":\"2024-11-01T09:16:08+00:00\",\"dateModified\":\"2024-11-01T11:38:52+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33398\/\"},\"wordCount\":403,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"Java Coding Test\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/33398\/\",\"url\":\"https:\/\/atmokpo.com\/w\/33398\/\",\"name\":\"Java Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:16:08+00:00\",\"dateModified\":\"2024-11-01T11:38:52+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/33398\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/33398\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/33398\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Coding Test Course, Segment Tree\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/33398\/","og_locale":"ko_KR","og_type":"article","og_title":"Java Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Hello! In this article, we will learn about the Segment Tree, which is one of the algorithms that can be useful in coding tests using Java. The segment tree is primarily used to efficiently handle range queries and range updates. In this article, I will explain the basic concept of segment trees, example problems related &hellip; \ub354 \ubcf4\uae30 \"Java Coding Test Course, Segment Tree\"","og_url":"https:\/\/atmokpo.com\/w\/33398\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:16:08+00:00","article_modified_time":"2024-11-01T11:38:52+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"2\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/33398\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/33398\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Java Coding Test Course, Segment Tree","datePublished":"2024-11-01T09:16:08+00:00","dateModified":"2024-11-01T11:38:52+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/33398\/"},"wordCount":403,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["Java Coding Test"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/33398\/","url":"https:\/\/atmokpo.com\/w\/33398\/","name":"Java Coding Test Course, Segment Tree - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:16:08+00:00","dateModified":"2024-11-01T11:38:52+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/33398\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/33398\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/33398\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Java Coding Test Course, Segment Tree"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33398","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=33398"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33398\/revisions"}],"predecessor-version":[{"id":33399,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/33398\/revisions\/33399"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=33398"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=33398"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=33398"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}