<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Obed Tandadjaja on Medium]]></title>
        <description><![CDATA[Stories by Obed Tandadjaja on Medium]]></description>
        <link>https://medium.com/@obed.tandadjaja?source=rss-d0461cc66ffb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dfHGeHhsEil7iDht7ieYzw.jpeg</url>
            <title>Stories by Obed Tandadjaja on Medium</title>
            <link>https://medium.com/@obed.tandadjaja?source=rss-d0461cc66ffb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:04:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@obed.tandadjaja/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Interview Guide: Identify Problem Constraints]]></title>
            <link>https://medium.com/@obed.tandadjaja/interview-guide-identify-problem-constraints-b6df51d25c66?source=rss-d0461cc66ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6df51d25c66</guid>
            <category><![CDATA[interview-techniques]]></category>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Obed Tandadjaja]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 03:36:46 GMT</pubDate>
            <atom:updated>2021-10-25T03:43:29.126Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><ul><li>Always remember to ask clarifying questions. For some problems, interviewers intentionally hide problem constraints/details to see if you dive into the implementation or not (mark of an inexperienced engineer).</li><li>Just like programming in general, it is crucial for you to fully understand the problem before coming up with a solution.</li><li>Use problem constraints to your advantage. You only need to solve the question within its constraints.</li><li>Knowing the constraints allows you to decide on which data structure to use, which algorithm to use, and which trade-offs to make (e.g. accuracy for the sake of speed, performance for the sake of space, etc.).</li></ul><p>Source: Google L3 question.</p><h3>Question</h3><p>Given an array of numbers containing integers, find the duplicate number in the array. The solution should have a linear time-complexity and a space-complexity of O(1), i.e. solve it in-place.</p><pre>Example:</pre><pre>Input: [1, 1, 2, 3, 4, 5]<br>Result: [1] // the duplicated number</pre><p>Looking at the question briefly, you might be tempted to:</p><ul><li>dive into the brute-force solution by implementing a nested for loop to find the duplicates — O(N²) where N is the length of the input array.</li><li>To improve it, you might be looking into sorting the array and then iterate the sorted array to see if there is any same neighboring elements — O(NlogN).</li><li>You will soon realize that solving the question linearly and in-place is very hard and that you might be wasting a lot of time trying to solve something that the interviewer does not expect you to.</li></ul><p>Before jumping into the implementation, you should <strong>always remember</strong> to ask clarifying questions to your interviewer such as:</p><ul><li>What is the range of the numbers in the array?</li><li>Can the number in the array be floats or doubles?</li><li>How large can the array be?</li><li>How many duplicates can there be in the array? Can we guarantee that there is only one?</li><li>Is the array mutable?</li></ul><p>Depending on the interviewer’s answer to your clarifying questions you can modify your solutions accordingly.</p><h3>Modified question #1</h3><p>Constraints:</p><ul><li>Only 1 duplicate number.</li><li>Size of array is N.</li><li>Number range: `1 — N` (inclusive).</li></ul><p>With the above constraints, the problem becomes more managable to solve. For example, since there is only going to be 1 duplicate number, we can use `XOR (^)` to help us find duplicates. `XOR` is useful such that it is evaluated to 0 when it XORs itself, see below for more details:</p><pre>5 ^ 5 = 0<br>5 ^ 5 ^ 5 = 5<br>5 ^ 5 ^ 5 ^ 5 = 0<br>5 ^ 5 ^ 5 ^ 5 ^ 5 = 5</pre><pre>5 ^ 3 ^ 3 ^ 5 = 0<br>5 ^ 3 ^ 3 ^ 5 ^ 3 = 3</pre><p>This is because XOR cancels out the 1s in the binary format when both are present and since each number has a different binary value, the result will always be non zero if it does not have a corresponding pair. Take the example of `5 ^ 3 ^ 5` below:</p><pre>5 = 101<br>3 = 011</pre><pre>5 ^ 3 ^ 5 = (101 ^ 011) ^ 101 <br>          = 110 ^ 101<br>          = 011<br>          = 3</pre><p>Because the size of the array is `N` and the number range is `1 — N`, there is a pair between the index and the value. See below:</p><pre>Index: [0, 1, 2, 3, 4, 5]<br>Value: [1, 2, 3, 4, 5, 5]</pre><p>You can then just XOR the indices and the value to get the duplicated value. See below for the final code solution:</p><pre>public int findDuplicate(int[] input) {<br> int output = 0;<br> for (int i = 0; i &lt; input.length; i++) {<br> output ^= i;<br> output ^= input[i];<br> }<br> return output;<br>}</pre><h3>Modified question #2</h3><p>Constraints:</p><ul><li>Multiple duplicates in the array.</li><li>Size of the array is N.</li><li>Number range: `1 — N` (inclusive).</li></ul><p>Since there are multiple duplicates in the array, we cannot use the XOR method from the previous solution. We will need to come up with a way to memoize the values we have seen in the past in the array itself. The best way to do this is to have some kind of `Set&lt;Integer&gt;` to mark seen values.</p><p>Knowing that the number range is from `1 — N`, we know that the indices of the array contains the number from `1 — N`. Additionally, since we know the inputs are always positive numbers, we can mark them as seen by making the value for the index negative. To make this point clearer, see below for a simple example:</p><pre>Index: [0, 1, 2]<br>Value: [1, 2, 2]</pre><pre>Iteration 0 — Mark 1 as seen<br>Index: [0, 1, 2]<br>Value: [1, -2, 2]</pre><pre>Iteration 1 — Mark 2 as seen<br>Index: [0, 1, 2]<br>Value: [1, -2, -2]</pre><pre>Iteration 2 — Identified 2 as seen so return duplicate<br>Index: [0, 1, 2]<br>Value: [1, -2, -2] -&gt; returns 2</pre><p>See below for the final code solution:</p><pre>public int findDuplicate(int[] input) {<br> for (int i = 0; i &lt; input.length; i++) {<br> int currentValue = Math.abs(input[i]);<br> if (input[currentValue] &lt; 0) {<br> return currentValue;<br> }<br> input[currentValue] = -input[currentValue];<br> }<br> return -1;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6df51d25c66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reminder to self: Always start with a monolith]]></title>
            <link>https://medium.com/@obed.tandadjaja/reminder-to-self-always-start-with-a-monolith-e6dc1947982b?source=rss-d0461cc66ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6dc1947982b</guid>
            <category><![CDATA[startup-lessons]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Obed Tandadjaja]]></dc:creator>
            <pubDate>Sun, 15 Dec 2019 10:09:58 GMT</pubDate>
            <atom:updated>2019-12-21T08:53:52.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2AqwVarwq3je3pMs" /></figure><p>I am starting a series of articles about lessons that I picked up along the way as I try to build my own startup project. The first and foremost: always start with a monolith.</p><blockquote>Delay optimization</blockquote><p>I have always struggled with the quote above. If we can build things very scalable and optimized from the get-go then why not? I have always known that optimization comes at the cost of the slow ramp-up period, however, I did not know that optimization comes with a humongous Google Cloud bill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IQdKFqn_7oMb7ch1biyTA.png" /><figcaption>I wasted $300 in 1.5 months</figcaption></figure><p><strong>My mistake:</strong> starting my startup with microservices.</p><p>Do not get me wrong, sooner or later I will switch to microservices infrastructure since it is the way to go in order to make your web application scalable and maintainable in the long term. The benefits that microservices bring such as independent deployment, modularity, independent scaling, reduced build time, etc. (for more info: <a href="https://microservices.io/">https://microservices.io/</a>) make them necessary for large web applications.</p><p>What I did not know is that it comes with a large bill. Take a look at my simplified microservices infrastructure for my web app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTdOiZDktL8_OGCD1S58oA.png" /><figcaption>A simple application with React front-end and Go back-end</figcaption></figure><p>I am using Kubernetes as my container orchestration system, and the above infrastructure results in 8 deployments and 8 pods (one pod for each deployment) along with 2 databases.</p><p>Although this infrastructure is very performant (latency under ~150ms) and maintainable due to the loose decoupling of services, it is just too expensive to finance for early startup projects. The main concern for early startup projects is to test the market and see if the product latches. Having said so, the tech stack needs to be built in such a way that it does not cost too much and can provide a longer ramp-up period for the company.</p><h3>Why is microservices infrastructure so expensive?</h3><p>In my case, the problem was I am spinning services that are rarely used. For example, my external service and email service are only used on very few occasions such as reset passwords and sending analytics. However, since I assign one pod for every single application, I am essentially <strong>running 2 extra pods 24/7</strong> even though they are only serving one or two requests per day. This costs a lot of money.</p><p>Furthermore, the decoupling of the authentication and back-end databases are also very expensive. Each one costs around <strong>$20 per month</strong> since each database will need to spin up a new SQL instance.</p><h3>Solution: Always start with a monolith</h3><p>Microservices infrastructure is not the answer to everything. Do not drop the term and just expect it to wash all of your scalability and maintainability problems away. Start by assessing if it is the right time for your system to adopt the microservices infrastructure.</p><p>In my case, I do not need it right now. I just need as much ramp-period as possible to really test if my product is something that people want. There are ways to make a monolith just as performant and maintainable as microservices, and build it in such a way that when I do want to decouple it to microservices, there will only be minimal refactor work.</p><h3>Building monoliths with an eye for microservices infrastructure</h3><p><strong>Do not add code to your monolith rashly</strong>; be thinking about where and when it can be used in the future. Does this functionality needed by a lot of different actions? If yes, then we probably need to pull it out to its own module so that it can be pulled out to its own service in the future.</p><p>Take the example of my external service. The purpose of this service is to be the one-stop-shop for every request going out to third-party services. And because I know that multiple microservices will potentially need to talk to a third-party service then instead of building a version of the client in each individual microservice, it should be in its own service.</p><p><strong>Different modules should only talk to each other through a client</strong>: a single class that will propagate the request to its action handlers. This is particularly important since if you have an action that references a method in another module, it would make the eventual decoupling of the code to a microservice infrastructure harder in the future.</p><p>For example, if you have your authentication and back-end actions in the same codebase, you should not let your back-end action handlers to access authentication methods directly. Instead, you should have an AuthClient in your back-end module that will call the authentication method for you. In this way, we can easily pull out the authentication module to its own microservice and convert the AuthClient to a REST/RPC endpoint.</p><p><strong>Be careful with cross-database entity relationships. </strong>It can be really tempting to couple 2 entities together through an ORM relationship or a simple JOIN query. However, we need to double-check if these 2 entities will be in 2 separate databases in the future. If they have the potential to be in separate databases, then mutual JOIN queries or ORM relationships should be avoided as much as possible.</p><p><strong>Consider using separate containers in the same Kubernetes pod to run different services. </strong>This ensures that the code that you are writing will be microservice compatible since the code is already decoupled from the get-go. Furthermore, it will be very easy for you to pull out the service to its own dedicated pod.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I1qTM6Y6zbsvchZCL7drVg.png" /><figcaption>Final design</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6dc1947982b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I got into Google: Things I do differently]]></title>
            <link>https://medium.com/@obed.tandadjaja/how-i-got-into-google-things-i-do-differently-4dd26fb6485f?source=rss-d0461cc66ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dd26fb6485f</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[interviewing]]></category>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <dc:creator><![CDATA[Obed Tandadjaja]]></dc:creator>
            <pubDate>Mon, 14 Oct 2019 08:40:22 GMT</pubDate>
            <atom:updated>2019-10-17T18:20:21.415Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I got into Google: Things I did differently</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*2SHvjbU_EOCg8hlMBOXG9Q.jpeg" /><figcaption>The glorious hat all programmers strive to have</figcaption></figure><p>There are already a lot of articles out there from way more qualified individuals talking about how they got into Google. Most of them revolve around how they prepare for the interview: how much LeetCode they did and types of questions to focus on.</p><p>In this article, I want to focus on some things that I do differently; things that are really helpful to me, but not discussed in other articles. Hopefully, this article can be helpful to some of you out there.</p><h3><strong>Some Context</strong></h3><ul><li>I have 3 years of experience in the field, switching from front-end to full-stack to pure back-end along the way.</li><li>I graduated from a no-name school.</li><li>I had 3 months to study for the interview.</li><li>I was juggling work and interviewing at the same time. I was actually leading a massive project at the time so the time that I spend on studying must be very productive.</li><li>I did not want to spend a single penny. Not even for LeetCode premium.</li></ul><h3><strong>No LeetCode premium? Why?</strong></h3><p>I did not see much value for LeetCode premium at the time since in my opinion, the free version was more than enough. Besides, most of the FAANG questions are not locked so all you need to do is go to <strong>Glassdoor</strong>, <strong>Blind</strong>, <strong>LeetCode Discussion Page</strong>, etc. to find out what questions were asked recently and just search those on LeetCode.</p><p>Two months into preparing for the Google interview, I discovered <strong>InterviewBit</strong>, which I grew to like better than LeetCode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWm-hsxkbfTVFpNgy4Lklg.png" /><figcaption>InterviewBit UI — on the right panel you can see the hints section. On the top panel you can see the average solving time and your score.</figcaption></figure><p>Different from LeetCode, InterviewBit actually shows you questions from FAANG for <strong><em>free,</em></strong> but there aren’t as many compared to LeetCode.</p><p>What I really love about them is their <strong>Hints</strong> feature (see the right panel). They usually have a couple of hints from small, rough solution, to complete solution. <strong>For me, this is really helpful since this is exactly what is going to happen in an actual interview</strong>. On LeetCode, I would always go straight to community discussion to get the final answer. This feature trains my brain to work through the hint and not just skip to the answer.</p><p>They also have <strong>timer</strong> and <strong>points</strong> features that I think are really helpful. Interviews are usually measured by <strong>craftsmanship</strong>, <strong>execution</strong>, and <strong>communication</strong>. Time and points feature really help measure my execution. <strong>How much time do I spend solving this problem and how many tries I did before I get the question right</strong>. I highly recommend people not to treat coding question as if you are debugging a program (i.e. testing the code one bit at a time). <strong>Always try to answer the question with one code submission</strong>.</p><h3>Always treat it like an actual interview</h3><p>I cannot stress enough the importance of this. Try to replicate as much of the actual interview experience with your practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*VVh2-jKs4QgvqIrokqqPxA.jpeg" /><figcaption>Putting this picture here just because people love pictures…</figcaption></figure><p><strong>Always try to answer the question with only one code submission</strong>. I know this is repeated from the last paragraph, but this is sooo important. Interviewers expect you to get the question in one try so always click that <em>Submit</em> button with caution as if you are submitting the code to the interviewer.</p><p><strong>Never submit a brute-force solution, always go for most optimal solutions</strong>. Let’s face it you will not pass the interview with a brute-force answer. LeetCode has a neat feature that compares your solution to other people; always shoot for 90+% faster than other submissions. Do not skip the question until you get this result.</p><p><strong>Have no longer than a 5-minute break in between questions</strong>. Interviews with FAANG are usually only 5-minute apart from each other. Really practice on your mental and intellectual stamina so that you will not be too drained on the day of the actual interview.</p><p><strong>Always be asking clarifying questions before you start coding</strong>. This is what differentiates experienced engineers from the rest. Always be thinking about edge cases and never make any assumptions when you start coding. This is an important skill to practice so do put down any questions you would potentially ask the interviewer as a <strong>comment </strong>in the code.</p><p><strong>Practice your Big O notation to finish off the question</strong>. Now that you have answered the question well, practice by looking back at the code and evaluate the time complexity of your solution. This will be asked by your interviewer so you should definitely practice this.</p><h3><strong>Always save your solutions</strong></h3><p>I like to save my solutions on a repo on my <a href="https://github.com/obedtandadjaja/interview_misc">Github</a>. I think this method is really beneficial since I like to take a break from coding 3 days before the actual interview (to reduce stress). During these 3 days, I would just go over my solutions on this repo, sometimes even printing some of the solutions just to read through during plane flights.</p><pre>// Question solution format that I usually follow</pre><pre>- Question prompt<br>- Examples</pre><pre>- Implementations<br>  - Implementation 1 (e.g. most efficient - dynamic programming)<br>  - Implementation 2 (e.g. less efficient - recursion with memo)<br>  - Implementation 3 (e.g. worst - recursion; brute force)</pre><pre>- How well it does (e.g. 90% better than other candidates)</pre><p>I also like to categorize the questions so that I can quickly search through them or study by category.</p><h3><strong>How to study?</strong></h3><p>Set up a schedule and really stick to it. In my case, I decided to leetcode for 2 hours after work during weekdays and 8 hours during weekends.</p><p>I would start the day by doing one easy question just to warm up and proceed to do medium questions throughout the day. Note that companies usually give medium questions and sometimes hard questions to more experienced candidates.</p><p><strong>Do not study in the same place where you chill or sleep</strong>. For me, this is very important since when I look at my bed or my sofa I am tempted to just sleep. I recommend going to a coffee shop or to the public library to study instead.</p><p><strong>Study where other people are studying</strong>. Looking at other people also working hard gives me a lot of motivation. This helps keep me from going to social media sites or Youtube and start wasting time.</p><h3>I got an onsite scheduled, what should I do?</h3><p>Checklist of things to bring:</p><ul><li>Print your <strong>code solutions</strong> if you want to go through them on the plane. Be looking for common patterns in the solution.</li><li>Pack up your <strong>formal attire</strong>, and leave the suit jacket behind. In my opinion, you can never overdress and so it is best to look clean and formal.</li><li>Pack up some <strong>sleeping pills</strong>. For me, I can get nervous or anxious before an onsite that I might lose some sleep because of them. Sleeping pills really help me ensure that I get enough sleep despite my anxiety.</li></ul><p>Things to do before the onsite:</p><ul><li>Wake up early and get a warm shower.</li><li>Sometimes I would skip shaving and leave some facial hair. This might not apply to you, but I have a baby face and so some facial hair can make me look older. I would do this when I was trying to apply for more senior-level positions.</li><li>Get a hearty breakfast, not too much, but not too little. The lunch break typically happen around 11:30 am to 12:00 pm so just have enough food to survive until then. Too much breakfast can cause stomach problems so try to avoid it (it happened to me once and I had stomachache during the interviews). Also, <strong>skip dairy</strong> just in case.</li><li><strong>Look up the names of your interviewers</strong> before the onsite and try to remember them. People like it when others call them by their names.</li><li><strong>Look up the projects of your lunch interviewer.</strong> This will help you get some topics to talk about during lunch.</li></ul><h3>Plot-twist: I didn’t join Google. I joined LinkedIn instead.</h3><p>Well, technically I got in since I passed the Hiring Committee and onto the team matching phase. However, Google’s team matching phase is very slow and can take a few months (depending on your level). I was really impatient to leave my startup job because I was so burnt out so I decided to join LinkedIn instead.</p><p>I hope this article can be helpful to some of you out there. Goodluck interviewing :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dd26fb6485f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Euler Problem #51]]></title>
            <link>https://medium.com/@obed.tandadjaja/project-euler-problem-51-e3e9db251a32?source=rss-d0461cc66ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3e9db251a32</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[project-euler]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Obed Tandadjaja]]></dc:creator>
            <pubDate>Fri, 09 Feb 2018 18:03:22 GMT</pubDate>
            <atom:updated>2018-02-09T18:03:22.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*rDTnfG2-KYhSHpy8VZuwHA.png" /><figcaption>Figure 1 — Proof of completion</figcaption></figure><p>Extremely enjoying <a href="https://medium.com/@ethan.jarrell">Ethan Jarrel’s</a> Project Euler articles, I decided to write one about a Project Euler problem that I really enjoyed.</p><p><strong>Disclaimer: Writing this article does not mean that my solution is the most efficient. I simply enjoyed the problem. Solution run time: 6 seconds.</strong></p><h3>Prime Digit Replacements</h3><blockquote>By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.</blockquote><blockquote>By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.</blockquote><blockquote><strong>Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family.</strong></blockquote><p>So basically we have to find a prime such that if we replace some of its digits with a digit (i.e. 1**1: 1111, 1221, 1331, 1441), we can get 8 other primes.</p><h3>Approaching the problem</h3><p>Just like any problem, we should <strong>delay any optimization</strong> until we are able to solve it. After all, what good is any optimization if we cannot solve the problem.</p><p>Obviously, the easiest way is to just <strong>brute-force</strong> the problem. Generating every possible wildcard string up to length <strong>L</strong>, filling them up with digits 0–9, and checking if those are primes.</p><pre>// 1. generate wildcard strings<br>1*, 2*, 3*, ..., 9*<br>1**, 2**, 3**, ..., 9**<br>1*1, 1*2, 1*3, ..., 1*9<br>1*1*, 1*2*, 1*3*, ..., 1*9*<br>etc.</pre><pre>// 2. filling them up<br>1*1* = 1111, 1212, 1313, 1414, 1515, ..., 1919<br>1*2* = 1121, 1222, 1323, 1424, 1525, ..., 1929</pre><pre>// 3. checking each one if they are primes<br>isPrime(1111), isPrime(1212), ...</pre><p>We can do better.</p><p>Let’s think about any potential optimizations. What are some of the bottlenecks in the above method?</p><p><strong>Let’s visit the first step</strong>, look at some of the wildcard strings we generated such as 1*0, 1*2, 1*4, 1*5, 1*6, 1*8. Can you spot any problems with these?</p><p>Correct. We know that these are <strong>always divisible by 2 or 5</strong> no matter what digit we put in the wildcard. And by eliminating these unnecessary strings, we can save a lot of processing power by preventing them from getting into the second and third step. But how can we eliminate these strings? AHHH I’m getting dizzy. Let’s just go to the second step first.</p><p><strong>The second step </strong>is a pretty straight-forward step. Can we find any bottlenecks here? We are simply replacing ‘*’ with 0–9 in this step. Wait, is it possible for us to combine this step with the first step? Nahh if so we are just generating all possible prime numbers from 2 to n. Not sure if there is any bottleneck in this step…</p><p><strong>Let’s go on to the third step</strong>, OH WOW it’s the classic isPrime problem. Immediately our brains go to solutions such as <a href="https://en.wikipedia.org/wiki/Fermat%27s_little_theorem">Fermat’s Little Theorem</a>, <a href="https://en.wikipedia.org/wiki/AKS_primality_test">AKS primality test</a>, <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a>, etc. So many options to choose from! Let’s choose AKS primality test since it’s one of the fastest primality test.</p><pre>// AKS Primality Test<br>def isPrime(n):<br>    if n == 1: <br>        return False<br>    if n == 2:<br>        return True<br>    if n == 3:<br>        return True</pre><pre>    if n % 2 == 0:<br>        return False<br>    if n % 3 == 0:<br>        return False</pre><pre>    i = 5<br>    w = 2</pre><pre>    while i*i &lt;= n:<br>        if n % i == 0:<br>            return False<br>        i += w<br>        w = 6-w</pre><pre>    return True</pre><p>Half way into writing the algorithm above, you brains should go “WAIT A MINUTE”. We are going to do the isPrime check over and over again! Why are we not saving these values? Dynamic programming enters…</p><p>Let’s just save these primes into an array. And because composite numbers are basically a product of two or more prime numbers (i.e. 70 = 2 x 5 x 7), we can determine the next prime using our existing ones!</p><pre>primes = []<br>primes.append(2)</pre><pre># lets go and find primes from 3-1000000<br>for x in range(3, 1000000):<br>    found = False<br>    for i in range(0, len(primes)):<br>        if x % primes[i] == 0:<br>            found = True<br>            break<br>        if primes[i] * primes[i] &gt; x:<br>            break<br>    if not found:<br>        primes.append(x)</pre><p>The isPrime function would just be searching if the prime is in the array. And because the array is in ascending order, we can use binarySearch for this.</p><pre>def binarySearch(prime):<br>    start = 0<br>    end = len(primes)<br>    middle = int((end + start)/2)<br>    <br>    while(start &lt; end <br>          and primes[middle] != prime <br>          and middle &lt; len(primes)):<br>        if primes[middle] &lt; prime:<br>            start = middle+1<br>        else:<br>            end = middle-1<br>        middle = int((end + start)/2)<br>    <br>    if middle &lt; len(primes) and primes[middle] == prime:<br>        return middle<br>    else:<br>        return -1</pre><p>Nice! Let’s go back to the <strong>first step</strong> and see if we have additional insights into bottlenecking this problem. Again, your brains should go “WAIT A MINUTE”. We now have an array of primes… We are trying to make sure all the wildcard strings are primes… <strong>WE CAN JUST DERIVE THE WILDCARD STRINGS FROM THE PRIMES</strong>! Hallelujah! The Lord lives! God is good!</p><p>OKOK now all we have to do is to generate any possible wildcard strings from a prime. We can use recursion for this!</p><pre>wildcards = []</pre><pre># generate every possible wildcard strings<br>def genWildcardStrings(s, index):<br>    if index &gt; 0:<br>        wildcards.append(s)<br>    for x in range(index, len(s)):<br>        genWildcardStrings(replaceCharWithAsterisk(s, x), x+1)</pre><pre># replace a character with &#39;*&#39;<br>def replaceCharWithAsterisk(s, index):<br>    return s[0:index] + &#39;*&#39; + s[index+1:]</pre><p>OK now <strong>piecing it up together</strong>.</p><ol><li>we find prime numbers within 3–1,000,000.</li><li>we loop through this prime array and generate wildcard strings for each.</li><li>fill up the asterisks with digits from 0–9 and check if each is a prime.</li><li>If it is, then increment the counter by 1.</li><li>If the counter is bigger or equal to 8, then print the prime and the wildcard string and exit the program.</li></ol><pre>import time</pre><pre># global vars<br>start = time.time()</pre><pre>wildcards = []</pre><pre>primes = []<br>primes.append(2)</pre><pre># generate every possible wildcard strings<br>def genWildcardStrings(s, index):<br>    if index &gt; 0:<br>        wildcards.append(s)<br>    for x in range(index, len(s)):<br>        genWildcardStrings(createPlaceholder(s, x), x+1)</pre><pre># replace a character with &#39;*&#39;<br>def createPlaceholder(s, index):<br>    return s[0:index] + &#39;*&#39; + s[index+1:]</pre><pre># binarysearch for searching prime<br>def binarySearch(prime):<br>    start = 0<br>    end = len(primes)<br>    middle = int((end + start)/2)<br>    <br>    while(start &lt; end <br>          and primes[middle] != prime <br>          and middle &lt; len(primes)):<br>        if primes[middle] &lt; prime:<br>            start = middle+1<br>        else:<br>            end = middle-1<br>        middle = int((end + start)/2)<br>    <br>    if middle &lt; len(primes) and primes[middle] == prime:<br>        return middle<br>    else:<br>        return -1</pre><pre># lets go and find primes from 3-1000000<br>for x in range(3, 1000000):<br>    found = False<br>    for i in range(0, len(primes)):<br>        if x % primes[i] == 0:<br>            found = True<br>            break<br>        if primes[i] * primes[i] &gt; x:<br>            break<br>    if not found:<br>        primes.append(x)</pre><pre># loop through primes<br>for x in range(0, len(primes)):<br>    wildcards = []<br>    # generate all possible wildcard strings for that prime<br>    genWildcardStrings(str(primes[x]), 0)<br>    # loop through all possible wildcard strings<br>    for y in range(1, len(wildcards)):<br>        count = 0</pre><pre>        # fill up the asterisk with 0-9<br>        for z in range(0, 10):<br>            num = int(wildcards[y].replace(&#39;*&#39;, str(z)))<br>            if binarySearch(num) &gt;= 0:<br>                count += 1</pre><pre>        # if counter is at least 8 then print and exit program<br>        if count &gt;= 8:<br>            print(primes[x])<br>            print(wildcards[y])<br>            print(&quot;Elapsed time: &quot; + str(time.time() - start))<br>            exit(0)</pre><p>Running this we get the following results:</p><pre>100109<br>***109<br>Elapsed time: 23.68400001525879</pre><p>This result is valid because 000109, 111109, 222109, 444109, 555109, 666109, 777109, 888109 are primes. But then when we go to Project Euler website put the answer in (i.e. 109 from 000109), <strong>they do not accept it as the right answer</strong>. WHAT WHAT WHAT</p><p>You know what maybe they are not happy that we reduce 000109 to 109… We should have a check for reduced numbers and make sure that these do not get counted by our counter.</p><pre># fill up the asterisk with 0-9<br>for z in range(0, 10):<br>    num = int(wildcards[y].replace(&#39;*&#39;, str(z)))</pre><pre>    # skip reduced numbers<br>    if len(str(num)) &lt; len(wildcards[y]):<br>        continue</pre><pre>    if binarySearch(num) &gt;= 0:<br>        count += 1</pre><p>OK running this again we get a different result:</p><pre>120383<br>*2*3*3<br>Elapsed time: 32.7810001373291</pre><p>Nice! Submitting the first prime of this wildcard string (i.e. <strong>121313</strong>) on Project Euler and OHH YEAHH we solved the problem.</p><h3>Delayed Optimization</h3><p>32.8 seconds is a long time. Not satisfied with this runtime, I decided to go back and see if I can tackle some more bottlenecks along the way.</p><p>I begin to debug each step; printing each generated prime and wildcard strings. And I found something disturbing…</p><p>On the first 5 primes (i.e. 2, 3, 5, 7, 11), we generated the following wildcard strings:</p><pre>2: [ &#39;*&#39; ]<br>3: [ &#39;*&#39; ]<br>5: [ &#39;*&#39; ]<br>7: [ &#39;*&#39; ]<br>11: [ &#39;*1&#39;, &#39;**&#39;, &#39;1*&#39; ]</pre><p>Oh no, it seems like we did not take care of wildcard string duplicates. We should really record the ones that we have searched and make sure they don’t get searched again.</p><p>The easiest way to do this is by using a HashSet where add and lookup is O(1). We can just store our searches and lookup if we have searched a wildcard string.</p><pre>searched = set()</pre><pre># generate every possible wildcard strings<br>def genWildcardStrings(s, index):<br>    if index &gt; 0 and s not in searched:<br>        wildcards.append(s)<br>        searched.add(s)<br>    for x in range(index, len(s)):<br>        genWildcardStrings(createPlaceholder(s, x), x+1)</pre><p>So the whole code would look like the following</p><pre>import time</pre><pre># global vars<br>start = time.time()</pre><pre>wildcards = []</pre><pre>primes = []<br>primes.append(2)</pre><pre>searched = set()</pre><pre># generate every possible wildcard strings<br>def genWildcardStrings(s, index):<br>    if index &gt; 0 and s not in searched:<br>        wildcards.append(s)<br>        searched.add(s)<br>    for x in range(index, len(s)):<br>        genWildcardStrings(createPlaceholder(s, x), x+1)</pre><pre># replace a character with &#39;*&#39;<br>def createPlaceholder(s, index):<br>    return s[0:index] + &#39;*&#39; + s[index+1:]</pre><pre># binarysearch for searching prime<br>def binarySearch(prime):<br>    start = 0<br>    end = len(primes)<br>    middle = int((end + start)/2)<br>    <br>    while(start &lt; end <br>          and primes[middle] != prime <br>          and middle &lt; len(primes)):<br>        if primes[middle] &lt; prime:<br>            start = middle+1<br>        else:<br>            end = middle-1<br>        middle = int((end + start)/2)<br>    <br>    if middle &lt; len(primes) and primes[middle] == prime:<br>        return middle<br>    else:<br>        return -1</pre><pre># lets go and find primes from 3-1000000<br>for x in range(3, 1000000):<br>    found = False<br>    for i in range(0, len(primes)):<br>        if x % primes[i] == 0:<br>            found = True<br>            break<br>        if primes[i] * primes[i] &gt; x:<br>            break<br>    if not found:<br>        primes.append(x)</pre><pre># loop through primes<br>for x in range(0, len(primes)):<br>    wildcards = []<br>    # generate all possible wildcard strings for that prime<br>    genWildcardStrings(str(primes[x]), 0)<br>    # loop through all possible wildcard strings<br>    for y in range(1, len(wildcards)):<br>        count = 0</pre><pre>        # fill up the asterisk with 0-9<br>        for z in range(0, 10):<br>            num = int(wildcards[y].replace(&#39;*&#39;, str(z)))<br>            if len(str(num)) &lt; len(wildcards[y]):<br>                continue<br>            if binarySearch(num) &gt;= 0:<br>                count += 1</pre><pre>        # if counter is at least 8 then print and exit program<br>        if count &gt;= 8:<br>            print(primes[x])<br>            print(wildcards[y])<br>            print(&quot;Elapsed time: &quot; + str(time.time() - start))<br>            exit(0)</pre><p>Running this modified code, we get the following result:</p><pre>120383<br>*2*3*3<br>Elapsed time: 6.501099917984009</pre><p><strong>OH YEAH WE GOT IT DOWN TO 6 SECONDS. </strong>Mission accomplished.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3e9db251a32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hack around to read The New York Times for FREE]]></title>
            <link>https://medium.com/@obed.tandadjaja/how-i-read-the-new-york-times-everyday-for-free-3c1f4e8e2fe4?source=rss-d0461cc66ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c1f4e8e2fe4</guid>
            <category><![CDATA[lifehacks]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Obed Tandadjaja]]></dc:creator>
            <pubDate>Fri, 02 Feb 2018 00:48:44 GMT</pubDate>
            <atom:updated>2018-02-05T20:24:36.207Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_8Mz9njeV5fLi0J6kh7bw.png" /></figure><p>I like to start the day by reading the news, and not just any news, I want to read <strong>credible news</strong>. And for me, no news source is more credible than the New York Times, but the problem is they only let you read 5 articles every month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xj5HKBcDJ8zxP3aU8vIU6g.png" /></figure><p>When I get the popup shown above, I was confused on how they keep track of the number of articles I read during the month. And because I do not have an account on their site, they should not be able to track my reading history.</p><p>If so, then the only explanation is they are doing the <strong>tracking on the client-side via Cookies</strong>.</p><p>Knowing this, we can easily <strong>clear our browser cookies</strong> to delete their tracking record. The number of articles remaining will go back to 5 once we have done so.</p><p>By clearing our browser cookies, we are “fooling” the site into thinking that we visited the site for the first time.</p><h3>Problem with doing validation on Client-Side</h3><p>Users can easily manipulate your data. Yes, even when you encrypt it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xeJ05-BZALhnYPh0Et-fw.png" /></figure><p>Take a look at what New York Times does with their cookies. They do a lot of encryption and probably some encoding on top of it. And, don’t get me wrong, this does prevent users from viewing the data, but it does not stop them from tampering the data (i.e. in this case, clearing the entire thing).</p><p>You can prevent data tampering to a certain extent. Developers often resort to <a href="https://en.wikipedia.org/wiki/Message_authentication_code">MAC</a>, by hashing the entire thing with a secret key stored in the server, to ensure that the data has not been tampered with.</p><p>But even so, you cannot stop them from clearing their cookies.</p><h3>Is there a better way of doing this?</h3><p>No. Not really. Unless New York Times is willing to track their visitors by their IP Address by storing them on their database.</p><p>Even so, this solution has some gotcha’s.</p><ol><li><strong>Too much trouble</strong>. Not many people understand this concept enough to exploit it. You end up spending a ton of money, trying to prevent a small group of people from reading your news for free.</li><li><strong>Too much data</strong>. Tracking every IP address that goes through the site within the month is a lot of data. Especially when sites like Google News are referencing your articles in their site, thus bringing in more traffic to your website.</li><li><strong>Too many computers</strong>. There are simply too many Internet-connected-computers for every computer to have its own unique IP address. IPv4 uses 32-bit IP addresses, this provides roughly 4 billion IPv4 addresses. The number of connections in the world have passed this number, thus making IPv4 addresses no longer unique. Sure, developers have tried to come up with solutions like <strong>NAT (Network Address Translation)</strong> and <strong>IPv6</strong>. However, not everyone has embraced these solutions to make this solution work seamlessly.</li></ol><h3><strong>How do I clear my browser cookies?</strong></h3><p>You can find great resources <a href="http://lmgtfy.com/?q=how+do+i+clear+my+browser+cookies%3F">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c1f4e8e2fe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>