# yasint.dev — full text > Every published post, newest first, concatenated as markdown. # How to write an eval for your agent > Learn how to test an AI agent when it never gives you the same answer twice, using a small refund desk as an example. August 15, 2026 · 44 min read · https://yasint.dev/write-an-eval-for-your-agent/ Tags: ai, agents, evals, engineering --- An **eval** is a test suite for software that doesn't give you the same answer twice. If you are building anything on top of a language model, you need one, and thankfully it is far simpler than the word makes it sound. If the word makes you feel behind, I felt that too. When I first ran into evals last year my honest reaction was that everyone else had clearly been doing this for years and nobody had thought to mention it. > **Intended audience** > > It helps if you have written a unit test before, but that's all you need. No machine learning background required. If you know what a function call is, you can digest this one just fine. We are going to build a small agent, write an eval for it, and then run the thing. The running is the part that surprised me. First, let me walk you through a small example to see why the usual kind of test falls apart. Software used to be dynamic. Now it breathes. ## Meet Acme's refund desk Imagine a company called **Acme Supplies**. They sell office chairs, and their support inbox is handled by an agent we will call **Otto**.
One key takeaway was how important it is to _stay curious_. According to Wallace, curiosity is what keeps the doors open. When you’re open to new opportunities, new ideas, and even unexpected changes, that’s when real growth happens. He encouraged us to never shy away from uncertainty but to embrace it, because the best things often come from the paths we never thought we’d take, drawing from his own career and life experiences.
Wallace also touched on the balance between our actions and our thoughts. He emphasized that we often prepare for potential risks, investing time and resources into safeguarding our futures. However, this can lead to a dilemma: while we might make prudent choices to mitigate risk, we can’t predict whether those preparations will ultimately be necessary. This illustrates the challenge of navigating uncertainty—how to weigh the potential for loss against the possibility that our worries might never materialize. It was refreshing to hear someone with his experience say that success isn’t about following a set blueprint, dictated by anyone else, but about exploring, learning, and being willing to step through new doors when they open. He even mentioned how this idea ties back to his [books](https://scholar.google.com/citations?user=U1WExVYAAAAJ&hl=en), which delve into these themes of uncertainty, decision-making, and adapting in both personal and professional contexts. --- # Debugging a running Java app in Docker > How to Attach a Debugger to a Running Java Application Inside a Docker Container May 29, 2024 · 5 min read · https://yasint.dev/debugging-running-java-app-docker/ Tags: java, docker, debugging --- Debugging a Java application running inside a Docker container can be a straightforward process if you follow these simple steps. In this guide, I will walk you through the necessary steps to attach a debugger to your Java application. ## Java application First of all, let's create a sample Java application to debug. We'll be using [Javalin](https://javalin.io/) for creating a simple API. ## Project structure Here is the folder structure for our project: ```txt . ├── Dockerfile ├── pom.xml ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── dev/ │ │ │ └── yasint/ │ │ │ └── Main.java │ │ └── resources │ └── test/ │ └── java └── target ``` ## Maven configuration (`pom.xml`) Create the pom.xml file with the following content: ```xml isClosedHonestly, I'm not a fan of this approach. Having worked with many React codebases, I find it _frustrating_ to wade through such code. It feels like being in a maze, trying to trace back where everything comes from and where it's supposed to go. But nonetheless, we sometimes have to deal with it, especially when working with older React codebases where this pattern is all too common.
This is the scenario we are aiming to refactor in later sections to avoid deep prop drilling. ## Navigating away from deep prop drilling In the React world, deep prop drilling is like navigating a maze. But no worries, we have smart ways to bypass this. We’re going to dive into two common techniques. ## Using React Context This is our first approach to avoid deep prop drilling. React Context acts like a messenger, delivering props directly to components, no matter their level in the tree. It's a straightforward way to share data across different components without the hassle of passing props through each level. React Context allows you to share values like state and functions across your component tree without having to pass props down manually at every level. To use React Context, you first create a context using `createContext`. Then, you wrap your component tree with the context itself, `Instead of consuming the context directly in the `Child`, we create a separate `ThemeToggle` component. In component composition, instead of embedding all logic within a single component or passing props deeply, we break down our UI into smaller, reusable components. Each component takes care of its own functionality, leading to a cleaner and more modular structure.
This approach not only simplifies the component structure but also enhances reusability and maintainability. Alongside component composition, state management libraries can be used selectively when necessary to further _streamline_ state handling in your React application. Now, shall we? ```js const ThemeToggle = ({ theme, setTheme }) => { const toggleTheme = () => { setTheme(theme === "light" ? "dark" : "light"); }; return ( ); }; const Grandparent = ({ children }) => (Given a square matrix $A$ any vector $v$ is considered an eigenvector of $A$ if $v$ is not the zero vector and there is some scalar $\lambda$ such that applying $A$ to $v$ results in a scalar multiple of $v$, i.e., $v$ stays on the same line through the origin. In equation form, this is written as: $A \cdot v = \lambda \cdot v$, where $"\cdot"$ denotes the multiplication operation (either matrix multiplication or scalar multiplication, depending on context).
$\lambda$ is the eigenvalue corresponding to the eigenvector $v$ in the above equation. It represents the scalar multiple by which the eigenvector is _stretched_ or _compressed_ (if you can't recall linear transformations you can refer [Khan Academy](https://www.khanacademy.org/math/linear-algebra)'s Matrix Transformations lecture for a refresher). To find the eigenvalues of a matrix $A$, we follow two steps. First we set up the characteristic equation, and then we solve for $\lambda$: - ☝️ **Characteristic Equation:** You set up the equation $det(A-\lambda \cdot I)=0$, where $det$ represents the determinant of a matrix, and $I$ is the identity matrix of the same size as $A$. This equation is derived from the eigenvector equation $A \cdot v= \lambda \cdot v$ and the fact that $v$ is non-zero. - ✌️ **Solve for $\lambda$**: Solving the characteristic equation will give you the eigenvalues $\lambda$ of the matrix $A$. Once the eigenvalues $\lambda$ are known, the eigenvectors can be found by: - **Substitution:** For each eigenvalue $λ$, you substitute $\lambda$ back into the equation $A \cdot v= \lambda \cdot v$ (which can be rewritten as $(A− \lambda \cdot I) \cdot v=0)$ and solve for $v$. - **Solving the System:** Typically, you'll get a system of linear equations for $v$, which you'll need to solve. Any non-zero vector that satisfies the system of equations is considered an eigenvector corresponding to the eigenvalue $\lambda$. --- Let's consider a `2x2` matrix $A = \begin{bmatrix} 4 & 1 \\ 2 & 3 \end{bmatrix}$ 1. Characteristic Equation: First, we find the determinant of $A - \lambda \cdot I$ {/*@formatter:off*/} $$ det(A - \lambda \cdot I) = det \begin{pmatrix} \begin{bmatrix} 4 & 1 \\ 2 & 3 \end{bmatrix} - \lambda \cdot \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} \end{pmatrix} \\~\\ = det \begin{pmatrix} \begin{bmatrix} 4-\lambda & 1 \\ 2 & 3-\lambda \end{bmatrix} \end{pmatrix} \\~\\ = (4-\lambda)(3-\lambda) - (2)(1)=\lambda^2 - 7\lambda + 10 $$ {/*@formatter:on*/} 2. Solving for $\lambda$: We solve $\lambda^2 - 7\lambda + 10 = 0$ to find the eigenvalues. The solutions to this quadratic equation are the eigenvalues of $A$, which are $\lambda = 5$ and $\lambda = 2$. Now comes the real magic. We can find the eigenvectors by plugging each eigenvalue into the equation $(A− \lambda \cdot I) \cdot v=0$ and solving for $v$. For $\lambda = 5$: $$ \begin{bmatrix} -1 & 1 \\ 2 & -2 \end{bmatrix} \cdot \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix} $$ The system simplifies to $-v_1 + v_2 = 0$, so one eigenvector _could_ be $v = [1, 1]$ for $\lambda = 5$. $$ \begin{bmatrix} 2 & 1 \\ 2 & 1 \end{bmatrix} \cdot \begin{bmatrix} v_1 \\ v_2 \end{bmatrix} = \begin{bmatrix} 0 \\ 0 \end{bmatrix} $$ Similarly, for $\lambda = 2$, the system simplifies to $2v_1 + v_2 = 0$, so one eigenvector _could_ be $v = [1, -2]$ for $\lambda = 2$ This process reveals the eigenvalues $\lambda=5$ and $\lambda=2$, with corresponding eigenvectors $[1,1]$ and $[1,−2]$, respectively. Each eigenvector is associated with one eigenvalue, and these vectors indicate the "directions" in which the linear transformation represented by matrix $A$ acts by stretching/compressing, without rotating. --- Using `numpy` to find the eigenvalues and eigenvectors. ```python caption="I used 'np.linalg.eig' here and this method is for general square matrices, and there are optimized versions like 'np.linalg.eigh' for symmetric or Hermitian matrices." A = np.array([[4, 1], [2, 3]]) ## The eigenvectors are normalized so their Euclidean norms are 1. eigenvalues, eigenvectors = np.linalg.eig(A) print("Matrix A:") print(A) print("\nEigenvalues:") print(eigenvalues.real) print("\nEigenvectors:") print(eigenvectors.real) ``` ```bash Output: Matrix A: [[4 1] [2 3]] Eigenvalues: [5. 2.] Eigenvectors: [[ 0.70710678 -0.4472136 ] [ 0.70710678 0.89442719]] ``` In this output, the eigenvalues are `5` and `2`, which match the mathematical solution I calculated. The eigenvectors in `numpy` are normalized (i.e., their "unit length" of 1 in Euclidean space), so they may look different from the one I calculate by hand, but they are indeed pointing in the same directions. The `.real` is there because since NumPy 2.5 `eig` always hands back complex arrays, so even these real eigenvalues would otherwise print with a `+0.j` tail.The first eigenvector is approximately $[0.707, 0.707]$, which points in the same direction as $[1,1]$, and the second eigenvector is approximately $[−0.447, 0.894]$, which lies on the same line as $[1,−2]$ (numpy just picked the opposite sign, which is still a valid eigenvector). The direction is the critical property of the eigenvector, not the magnitude.
We can verify this by normalizing the vector. It involves dividing each component of the vector by its length. For example, suppose the vector is $[1, -2]$. First, we calculate the magnitude ($m$) (Euclidean norm): $\small{m = \sqrt{(1)^2 + (-2)^2} = \sqrt{1+4} = \sqrt{5}}$ Then, divide each component of the original vector by this magnitude: $\text{normalized}\ \text{vector} = \begin{bmatrix} \frac{1}{\sqrt{5}},\frac{-2}{\sqrt{5}}\end{bmatrix}$ Or just use `numpy`. ```python ## Define the original vectors vectors = np.array([[1, 1], [1, -2]]) ## Function to normalize a vector def normalize_vector(vector): # Calculate its magnitude (Euclidean norm) magnitude = np.linalg.norm(vector) normalized_vector = vector / magnitude return normalized_vector ## Normalize the vectors and print the results for vector in vectors: normalized_vector = normalize_vector(vector) print(f"Original vector: {vector}") print(f"Normalized vector: {normalized_vector}\n") ``` Both approaches will give us the same normalized vector: ```bash Output: Original vector: [1 1] Normalized vector: [0.70710678 0.70710678] Original vector: [ 1 -2] Normalized vector: [ 0.4472136 -0.89442719] ``` Dassit 👋 ## Reading list - [Stanford Spectral Graph Theory](https://web.stanford.edu/class/cs168/l/l11.pdf) - [CMU: Spectral Graph Theory and its Applications](https://www.cs.cmu.edu/afs/cs/user/glmiller/public/Scientific-Computing/F-11/RelatedWork/Spielman/SpectTut.pdf) - [Yale Spectral Graph Theory](http://www.cs.yale.edu/homes/spielman/PAPERS/SGTChapter.pdf) --- # Java's fork/join framework > Java goes Forking Crazy! October 21, 2023 · 8 min read · https://yasint.dev/java-fork-join/ Tags: java, concurrency --- Hey there 👋! With multicore processors now standard, it's essential for high-performance applications to harness this power through effective concurrency. [Java's Fork/Join framework](https://docs.oracle.com/javase/tutorial/essential/concurrency/forkjoin.html), part of the `java.util.concurrent` package since JDK `7`, optimizes the efficiency of multi-threaded tasks, fully utilizing the capabilities of modern hardware. In this article, I'm going to delve into the **Fork/Join framework**, explaining its purpose, significance, and application, all illustrated with a practical example. ## What the fork? The Fork/Join framework is an implementation of the `ExecutorService` interface that helps developers solve problems using [divide-and-conquer algorithms](https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm). These algorithms work by breaking down a task into smaller, more manageable pieces, solving each piece separately, and then combining the results. In this framework, any **task can be forked (split)** into smaller tasks, and the **results can be joined** subsequently, hence the name "Fork/Join." You may wonder, "Why opt for the Fork/Join Framework when traditional threading is an option?" ## Hmm, why? Picture multitasking. But it's Java juggling your tasks with _finesse_! Aaaaand it's all about efficiency, and here's why: - - **Efficient Thread Utilization:** It makes use of a [work-stealing algorithm](https://en.wikipedia.org/wiki/Work_stealing), where idle threads "steal" tasks from busy threads' queues. This ensures that all threads are actively used, reducing overhead and improving performance. - **Handling Recursive Tasks:** The framework excels at handling recursive computations, a common scenario in _divide-and-conquer_ algorithms. - **Improved Scalability:** It's designed to scale well to available parallelism, which means better performance on multicore processors. ## How does it work? Consider a scenario where you're faced with an array of **10 tasks**, each representing operations that are resource-intensive, such as database or I/O operations. Fork/join is built for CPU-bound work, so blocking tasks like these belong in a pool of their own (or behind `ForkJoinPool.managedBlock`), but they make the splitting easy to watch. Your objective is to expedite the processing of these tasks efficiently without overburdening the system resources. Sequential execution is off the table due to time constraints, and a single thread can handle a maximum of two tasks consecutively. Intriguing challenge, isn't it? Let's tackle this problem by employing a _divide-and-conquer_ strategy.  As demonstrated, our goal is to systematically divide tasks until they're manageable enough, aligning with our defined threshold. Wondering how this translates into Java? Stay with me; it's simpler than it seems. First, let's establish our _base scenario_. Imagine a `Task` class, responsible for handling time and resource-intensive operations—think bulk updates, I/O, network calls, and more. Here's a glimpse of what it looks like: ```java name="Task.java" public class Task { private final int id; // Other necessary fields... public Task(int id) { this.id = id; } public void process() { // Note: exception handling omitted for brevity System.out.printf("Processing task %d...%n", id); Thread.sleep(TimeUnit.SECONDS.toMillis(3)); } } ``` However, we can enhance our approach by abstracting the `process()` method, leading us to define a `Computable` functional interface and implement it in our `Task` class, like so: ```java @FunctionalInterface public interface Computable { void process(); } public class Task implements Computable { // Existing code... } ``` Noice 😎! That's so much neater, isn't it? Next, we generate an array of random tasks, shifting our focus to the crux of the issue: **parallel execution**. ```java private Task[] generateTasks(int count) { Task[] tasks = new Task[count]; for (int i = 0; i < tasks.length; i++) { tasks[i] = new Task(i + 1); } return tasks; } ``` But how do we execute these tasks in parallel? Enter Java's Fork/Join framework. Here's a simplified guide: 1. Extend `RecursiveTaskI'll admit, there are times I get a bit too enthusiastic and end up complicating things more than necessary. And, oh boy, the maintenance! As in every codebase's foundational types shift and change, you've got to be vigilant, ensuring that the types you've "picked" are still vibing well. It's like keeping tabs on a growing chain of dependencies, but hey, that's the coder's life for you!
## The `Omit` type Think of `Omit` as the sibling of `Pick`. Instead of telling it what you want, you tell it what you don't want. It's like ordering a pizza and saying, **"Hold the olives 🤨."** Given a type $T$ and a set of properties $P$, the Omit operation can be represented as $T - P$. ```ts // User type from above type UserWithoutEmail = OmitWhen I first started using `Omit`, I was blown away by its precision—it's _super handy_ when I want to leave out just a thing or two, especially from those chunky types. Plus, it's a lifesaver in ensuring I don't accidentally toss in stuff I'd rather keep out. But, it wasn't all sunshine and rainbows.
In the beginning, I'd often jumble up `Omit` and `Pick` since they're kinda like two sides of the same coin. And, just like with Pick, I've realized I've got to be on constant alert, especially when my main types undergo changes. Part of that is on `Omit` itself: unlike `Pick`, it doesn't check that the keys you hand it exist on the type, so `OmitThis proposal enriches the set of methods on `Array.prototype` by introducing a suite of functions that operate on the array and return a new copy, instead of manipulating the original array. The newcomers to this function suite include [`toReversed()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed), [`toSorted()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted), [`toSpliced()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSpliced), and an additional method named [`with()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/with).
These methods are designed to mirror the behavior of existing methods [reverse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse), [sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), and [splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), and the typical array element replacement operation performed using bracket notation. However, these new methods ensure that the original array remains unaltered. ## `toSorted()` The `toSorted()` method, just like `sort()`, arranges the array elements in a certain order. The crucial difference is that **it does not modify the original array**. ```js let jumbledNumbers = [30, 10, 20]; console.log(jumbledNumbers); // Output: [30, 10, 20] let orderedNumbers = jumbledNumbers.toSorted(); console.log(orderedNumbers); // Output: [10, 20, 30] // The original array remains unchanged console.log(jumbledNumbers); // Output: [30, 10, 20] ``` ## `toSpliced()` Similarly, `toSpliced()` acts as a non-destructive version of splice(). It returns a new array, incorporating the changes specified by the arguments, while the original array stays intact. ```js let oldArray = ['🍎', '🍌', '🥭']; console.log(oldArray); // Output: ['🍎', '🍌', '🥭'] // In here we just say, start from index 1 and delete 0 elements, and insert '🍊' let newArray = oldArray.toSpliced(1, 0, '🍊'); console.log(newArray); // Output: ['🍎', '🍊', '🍌', '🥭'] // The original array remains unchanged console.log(oldArray); // Output: ['🍎', '🍌', '🥭'] ``` ## `with()` Additionally, the `with()` method is an invaluable tool that replaces an element at a specified index with a given value and returns a new array, without touching the original array. ```js let initialFruits = ['🍎', '🍌', '🥭']; console.log(initialFruits); // Output: ['🍎', '🍌', '🥭'] let updatedFruits = initialFruits.with(1, '🍊'); console.log(updatedFruits); // Output: ["🍎", "🍊", "🥭"] // The original array remains unchanged console.log(initialFruits); // Output: ['🍎', '🍌', '🥭'] ``` ## The motivation behind these new methods Incorporating these methods in the language specification echoes the increasing emphasis on promoting functional programming styles in JavaScript, where data is usually treated as immutable. This development is a welcome addition for developers who frequently need to perform operations on arrays but wish to keep the original arrays unmodified. For me personally, these new features significantly simplify array manipulation, particularly in scenarios where avoiding side effects is critical. By preventing [accidental mutations](https://sapegin.me/blog/avoid-mutation/), these methods make the code more predictable and easier to reason about, which is a key factor in reducing bugs and enhancing code readability. ## Conclusion The ECMAScript 2023 **'Change Array by Copy'** proposal introduces four powerful methods that align JavaScript with modern functional programming practices: `toReversed()`, `toSorted()`, `toSpliced()`, and `with()`. These non-destructive alternatives keep your original arrays untouched, making code more predictable and safer, especially when working with frameworks like React that rely on immutability. Supported in modern browsers (Chrome 110+, Firefox 115+, Safari 16+), in my opinion, these methods should be your default choice for array manipulation. Use the traditional mutating methods only when you explicitly need in-place modification. Happy coding! 🚀 --- # Integrating JUnit 5 in Maven projects > A practical guide to setting up JUnit 5 testing in Maven projects with modern best practices. May 25, 2023 · 4 min read · https://yasint.dev/integrating-junit-in-maven-projects/ Tags: java, testing --- [JUnit](https://junit.org/) is a simple, open-source framework to write and run repeatable tests in [Java](https://www.java.com/en/). It's an essential tool for any serious developer who wants to implement unit testing into their development lifecycle. Here's how you can integrate JUnit 5 into your Maven project. ## Prerequisites Before proceeding, make sure you have: - Java JDK installed (Java 8 or later) - [Apache Maven](https://maven.apache.org/) installed (3.6.3+) - Basic understanding of Maven project structure ## Step 1: updating the `pom.xml` file The first step to adding JUnit to your Maven project is to update your project's [`pom.xml` file](https://maven.apache.org/guides/introduction/introduction-to-the-pom.html). This XML file describes the software project being built, its dependencies, and the build order. You can include JUnit in your project by adding it as a dependency. Here is how you do that: ```xmlWhen we operate on a symlinked file, the soft link to the original file is broken, and `file-b.txt` becomes a separate regular file with its own copy of the content. You can see this result by executing `ls -la` command. But can we preserve the soft link and still edit the file in-place?
--- ## Following symlinks Yes, we can! According to the documentation, you can do this via the `--follow-symlinks` argument. If we re-execute the following and see the output, we'd get what we want. ```bash sed -i --follow-symlinks 's/[zpb]oo/bar/g' file-b.txt ``` With the `--follow-symlinks` argument, we can manipulate the original file in place without breaking the soft link. However, in BSD systems we cannot do this. Simply if you try to in-place edit a symbolic link it will throw an error called `sed: FILE.EXT: in-place editing only works for regular files`. --- ## Learn more If you're interested in learning more about it, I'd prefer you refer the [standard POSIX specification](https://pubs.opengroup.org/onlinepubs/9799919799/utilities/sed.html) and go from there onwards. Also, there's three answers by [Michael Klement](https://www.linkedin.com/in/mklement0/) on Stackoverflow related to `sed` ([1](https://stackoverflow.com/a/24276470) [2](https://stackoverflow.com/a/30066428) [3](https://stackoverflow.com/a/44864004)). Those three answers are just :chef-kiss:. --- # Asgardeo try it application > Learn how to use Asgardeo Try it Application to test out various authentication flows. September 6, 2022 · 10 min read · https://yasint.dev/introducing-asgardeo-try-it-application/ Tags: identity, iam, asgardeo --- Recently, folks at Asgardeo released a new feature called the **Asgardeo Try it Application** for quickly testing various login flows effortlessly. The best part of this feature is that you don't even need a functional application to get started with Asgardeo. How crazy is that, huh? > **Update (October 2026):** Asgardeo has since been renamed to WSO2 Identity Platform, so the Console, the docs and the `Try it` app itself now carry that name; the app shows up as **WSO2 Identity Platform Try It** under `Applications`, and you launch it from the **Try login with the Try It app** card on the Home page. I've kept Asgardeo throughout this post because that's what it was called when I wrote it, but the feature details follow today's Console, so it's Passkey wherever the old screens say Security Key or Biometrics. The screenshots and videos are a different matter. They still show the older Asgardeo Console, and you may have to hunt for a button or two that has since moved. Alright, now let's get into it. ## Getting started When you first log in to the Console application using your tenant admin credentials, it will present you with the following landing page. Once created, it will immediately redirect you to the `Try it` application. But for now, you can **close** that tab and head back to the Asgardeo Console. > **I already have applications, but where's Try it?** If you have accidentally deleted the `Try it` application, don't worry. You can recreate it from the **Home** page once again. Then Asgardeo will prepend a fresh copy to your existing application list. ## Configuring first-factor auth In every application, you'd either have email/password, social or entirely password-less authentication. Well, lucky for us; Asgardeo has all these options baked-in, so we can nibble instantly. I'll configure some social connections along with _email_ & _password_ and biometric authentication. You can refer below video for adding first-factor authentication to the `Try it` application flow. ## Connections configuration I already have `Google` & `GitHub` connections configured, and they are available for me to add to this application. However, if you don't see them, you should refer the [official Asgardeo documentation on configuring social connectors](https://wso2.com/identity-platform/docs/guides/authentication/social-login) or refer to my previous article about [Asgardeo JIT User Provisioning](https://www.yasint.dev/asgardeo-jit-user-provisioning#activate-federated-connections) for a quick tutorial. ## Add a user Also, note that I have created a Customer User in my default user store. You can easily do this by navigating to the `User Management` > `Users` section and clicking `Add User` > `Single User`. Or you can refer official [documentation on how to add users](https://wso2.com/identity-platform/docs/guides/users/onboard-users/#onboard-single-user). Okay, now we have the _first-factor authenticators_; it is time for us to **Try it**! We can instantly try this out by clicking the **"Try Login"** button. > **Alright, you've got me!** You saw that I'm not trying out Biometric Authentication (the last login option) because it requires setting up using the self-care portal before we can authenticate users, unless you turn on passkey progressive enrollment, which lets users enroll a passkey during login. And on the other hand, I want to expand a bit about **Asgardeo's Passkey** authenticator (previously called Security Key / Biometrics) in this article. > > Also, if you're using an Apple Chip, there's a hint mentioned on making it work in [Asgardeo in a password-less fashion using an iPhone & XCode](https://wso2.com/blogs/thesource/fido-passkeys-with-asgardeo/) written by [Thamindu](https://lk.linkedin.com/in/thamindu-dilshan-jayawickrama). Regardless, Asgardeo will seamlessly function with any functional FIDO2-compliant device on the fly. ## Passkeys 101 Asgardeo lets you configure **FIDO2** compliant devices to enable password-less authentication for your Users. In the above figure, we configured it in the first-factor configuration, and you can see that we can easily attach a FIDO authentication to the authentication sequence's first step. > **What's FIDO anyways?** > > FIDO (Fast Identity Online) is a set of open, standardized authentication protocols that ultimately eliminate passwords in application authentication developed by the [FIDO Alliance](https://fidoalliance.org/overview/) open industry association intended to ultimately eliminate passwords, which are often ineffective and outdated from a security perspective. Usually, when using FIDO, completing an initial registration process, and selecting a preferred method, your users can authenticate to your application by simply providing a **Fingerprint**, **Voice**, **FaceID**, **Security Key** or entering a **known PIN**, depending on the technology available on their computer or smartphone. ### How does it work underneath? FIDO protocols use standard [Public Key Cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography) techniques to authenticate users: the device signs a challenge from the server with a private key, and the server only ever holds the public key. Biometric data never leaves the user's device, and the private key never reaches the server (synced passkeys can copy it to the user's other devices through their password manager). ### What are the types of protocols? The FIDO Alliance has published three sets of specifications, and they are standardized on public key cryptography and namely: - - Universal Authentication Framework (UAF) - Universal Second Factor (U2F) - FIDO2 ### What Asgardeo Supports? Currently, Asgardeo supports FIDO2 and Asgardeo implements the newest set of specifications. These specifications are born through a joint effort between the [FIDO Alliance](https://fidoalliance.org/overview/) and the [World Wide Web Consortium (W3C)](https://www.w3.org/). FIDO2 is implemented with two open standards. And they are the FIDO Client To Authenticator Protocol (CTAP) and the W3C standard WebAuthn. These two work together to provide users with password-less authentication experiences or two-factor and multi-factor authentication experiences if additional protection is needed. ### Available Specifications They are different sets of user experiences that involve **Advanced Platform Authenticators**, like Biometrics (FaceID, TouchID) or PINs, and **Roaming Authenticators**, like Key Fobs or USB devices. The specifications included in FIDO2 are: - - WebAuthn - This defines a standard web API built into platforms and browsers to support FIDO2 authentication. It provides an interface for creating and managing Public Key credentials and can communicate with CTAP1 and CTAP2 authenticators. - CTAP1 - This is the new name for the FIDO U2F protocol. It provides users with a second-factor authentication experience, which requires that they plug security devices into their computers, or tap their devices near an NFC reader, to gain access to the application. - CTAP2 - This allows the authenticator to be used as both the first and second-factor authentication and can provide users with password-less authentication experiences or 2FA and MFA experiences if additional protection is needed. So here's how we configure a device as a first-factor biometric authentication (I don't have a proper Fido2 key, but my machine can act as a biometric authenticator). The following illustration is the initial authentication flow users go through to set up their devices for authentication using the [Asgardeo's My Account self-care portal](https://wso2.com/identity-platform/docs/guides/user-self-service).  Asgardeo docs also mention that we can configure FIDO2 password-less login for our application using two primary methods: - **Passkey**: An application user uses a FIDO2-supported authenticator to log in without entering a username or a password. **Identifier first + Passkey**: An application user enters a username first. Asgardeo verifies the identity from the username and prompts the user to use a FIDO2-supported authenticator to log in. > **Oh, Small Hiccup 🥺** > > Back when I wrote this, we could only use the `Identifier First` authenticator along with the `Magic Link` authenticator. Asgardeo forewarned us before we updated the authentication steps, saying that using it with any other authenticator could lead to unexpected behaviours.  That's no longer the case. `Identifier First` now pairs with other authenticators in the next step, and if you turn off **Allow passkey usernameless authentication** in the Passkey connection settings, users type their username first and then reach for their passkey. ## Configure second-factor auth Asgardeo allows us to add second-factor authentications such as TOTP and Email OTP to the `Try it` application's authentication flow. How convenient! Guess what? It doesn't require additional configurations to test it. We can directly jump into the playground. ## Hmm, something is odd We have configured second-factor authenticators, but we haven't considered the user experience of these authenticating options. Usually, when we configure multi-login options (i.e., email/password along with social connectors), it is best practice to avoid 2FA when a user authenticates from a federated connection. Here's why: -  When you log in through Google/GitHub connection, it usually prompts a notification on a device or email asking for validation whether only you are trying to log in (i.e., one-tap popups, mobile OTP code etc.). Now assume you completed either one of those. If everything goes as expected, then the flow is validated by Google. So, it doesn't make sense to initiate another 2FA/MFA verification in Asgardeo if you sign in using Google, correct? If we do that, it leads to a poor user experience. So, how can we fix those without making those mistakes in production? Well, lucky you, Asgardeo has thought about this already! ## Adaptive authentication to the rescue In Asgardeo, every application has its adaptive authentication script to manage its authentication flows. This script allows you to _enforce adaptive MFA_ in the login flow of your applications. For example, you can control authentication based on Group, `Sign-In-Option`, `New-Device`, and `IP`. We are particularly interested in the **Sign-In-Option-Based** script, where we can conditionally skip 2FA for **Google** and **GitHub**. The great thing about Asgardeo is that you can directly test it within the `Try it` application. It mimics what a user would go through, and you can deploy your application to production with _finesse_! ```js hideLang isWindow var localAuthenticator = "LOCAL"; var onLoginRequest = function (context) { executeStep(1, { onSuccess: function (context) { var step = context.steps[1]; if (step.idp == localAuthenticator) { executeStep(2); } } }); }; ``` Just turn on the `Conditional Authentication` switch and paste the above code snippet like the following: -  Once you update the script with the above, you can verify that Asgardeo skips `TOTP` and `Email OTP` for _Social Connectors_. FIDO is a local authenticator, so its step reports `LOCAL` and still gets the second factor; you'd need to check `step.authenticator` too if you want to skip it there. Well, now that we have covered the customization of Sign-in Methods in this `Try it` application, we are only left with the User Attributes and Advance Settings to cover. ## Other settings ## User attributes Specifically, the user attributes are pre-configured for the `Try it` application as it is a static application that aims to test the login flows. However, we can [enable and configure additional user claims/attributes](https://wso2.com/identity-platform/docs/guides/authentication/user-attributes/enable-attributes-for-oidc-app/#select-user-attributes) after integrating our actual application to Asgardeo. ## Advanced configurations Asgardeo allows you to control and test the User consent screen rendered during the sign-in and sign-out flow in an application. You can refer the [official Asgardeo documentation on user consent management](https://wso2.com/identity-platform/docs/guides/authentication/manage-consent-for-attributes/#get-consent-for-user-attributes) for more information. The best part is that you can do this in the `Try it` application. --- Well, now you know how to try out Asgardeo without an application. Asgardeo makes testing and experimenting with complex logical authentication flows in the application effortless. Thanks a bunch for reading 🥰! --- # Flatten error constraints > Recursively flatten properties of an array of objects. August 11, 2022 · 7 min read · https://yasint.dev/flatten-error-constraints/ Tags: typescript, algorithms --- So, last week I solved an easy problem but it was an interesting one! Uses of it applied in the world of frontend programming, and knowing how to solve such problems is quite valuable down the road when doing validation and processing-related tasks. ## Challenge statement The challenge statement is: given an array of error objects, we need to flatten its property constraints and transform them to a string array with the accurate property depth. In a nutshell, this is what we need to solve: - ```js const errors = [ { property: "applicant", children: [ { property: "identity", children: [ { property: "passport", children: [ { property: "expiryDate", children: [], constraints: { expired: "expiryDate is no longer valid", format: "expiryDate must be in the format DD/MM/YYYY" } }, { property: "issuedDate", constraints: { validity: "issuedDate must be greater than 01/01/2018", format: "issuedDate must be in the format DD/MM/YYYY" } } ], constraints: { prefix: "passport number should start with a capital letter", maxChars: "passport should be a string no more than 12 characters" } }, { property: "nationalIdentityCard", children: [], constraints: { isNumber: "nationalIdentityCard must be a 12 digit number" } } ] }, { property: "age", constraints: { isNumber: "age must be a number larger than 18" } } ] }, { property: "studentId", constraints: { isNumber: "studentId must be a number conforming to the specified constraints" } } ]; ``` And transform the above errors to this: - ```js const transformedErrors = { "applicant.identity.passport.expiryDate": [ "expiryDate is no longer valid", "expiryDate must be in the format DD/MM/YYYY" ], "applicant.identity.passport.issuedDate": [ "issuedDate must be greater than 01/01/2018", "issuedDate must be in the format DD/MM/YYYY" ], "applicant.identity.passport": [ "passport number should start with a capital letter", "passport should be a string no more than 12 characters" ], "applicant.identity.nationalIdentityCard": [ "nationalIdentityCard must be a 12 digit number" ], "applicant.age": ["age must be a number larger than 18"], studentId: [ "studentId must be a number conforming to the specified constraints" ] }; ``` A part of the challenge is to solve this using JavaScript. But we will utilize `TypeScript` to write our solution in the upcoming sections. ## Elaboration Well, it seems like a piece of cake, right? We can solve this quickly if we take a minute or two to understand its schematic structure correctly.  And if we transform this into more approachable static sorts we would get the following types. ```ts [key: string]: string; }; property: string; children?: Error[]; constraints?: Constraints; }; [key: string]: string[]; }; ``` Looking at the challenge statement example, we can see that not all Error objects contain the `children` property. Hence, we should understand that one or more depths will have zero `constraints` or `children` to flatten. Therefore, we can safely **ignore** such results from the transformed object. We can break down the problem into multiple steps to further simplify our approach. From my interpretation, we have four main tasks to focus on; and those are: - 1. Extract the string values from the `constraints` object. 2. Concatenate the children's `property` path along with depth. 3. Go through all the `children` errors. 4. Assign `constraints` to the path (if there are any). So how can we crack this? ## Solution We have to use either an iterative or a recursive to solve this problem. First, we can directly jump in and focus on the **1st step**, extracting the values from the constraints object. We can write a helper function that accepts a given `constraints` object and return its extracted strings. ```ts const extractConstraints = (constraints: Constraints): string[] => { const strings = []; for (const [, value] of Object.entries(constraints)) { strings.push(value); } return strings; }; ``` Then we can focus on **2nd step**, concatenating the children's property path along with depth. ```ts const concatProperty = (parent: Error, child: Error) => { return { ...child, property: `${parent.property}.${child.property}` }; }; ``` Then the **3rd step**, going through all the `children` errors. But before that, we need another top-level helper function to compose the algorithm. I will name it `transformError` with two parameters in place. The first parameter is an individual error itself and the second is our transformation result object. ```ts const transformError = (error: Error, result: Result) => { }; ``` Then we should first see whether there are any `children` available in this error object because remember, it can be optional. ```ts const transformError = (error: Error, result: Result) => { // Then check whether this error has children. if (error.children) { // Do something } } ``` So now, if the error has children then we should go through its `children` to recursively extract all their `constraints`. ```ts const transformError = (error: Error, result: Result) => { // Then check whether this error has children. if (error.children) { for (const child of error.children) { transformError(concatProperty(error, child), result); } } }; ``` This is great! Now that we are only left with the **4th step**, and we can easily append the `extractConstraints` at last. ```ts caption="Here you can see that we check for error.constraints existence because it's optional." const transformError = (error: Error, result: Result) => { // Then check whether this error has children. if (error.children) { for (const child of error.children) { transformError(concatProperty(error, child), result); } } let flatConstraints: string[] = []; // if the error has constraints, then extract them. if (error.constraints) { flatConstraints = extractConstraints(error.constraints); } // if and only if there's constraints, assign them. if (flatConstraints.length) { result[error.property] = flatConstraints; } }; ``` We consolidate the last three points into a single function called `transformError` because they are recurring tasks. By doing this, we should be able to iterate through all the errors and recurse all the children accurately. And finally, putting it all together, we get this: - ```ts [key: string]: string; }; property: string; children?: Error[]; constraints?: Constraints; }; [key: string]: string[]; }; /** * Given the constraints object, it returns an array of strings * that contains the values of that object. * @param {Constraints} constraints */ const extractConstraints = (constraints: Constraints): string[] => { const strings = []; for (const [, value] of Object.entries(constraints)) { strings.push(value); } return strings; }; /** * Concatenates child error property with the parent property. * @param {Error} parent * @param {Error} child */ const concatProperty = (parent: Error, child: Error) => { return { ...child, property: `${parent.property}.${child.property}` }; }; /** * Flattens a given error. If there's children and it * recurse through the children depth. * @param {Error} error * @param {Result} result */ const transformError = (error: Error, result: Result) => { // Then check whether this error has children. if (error.children) { for (const child of error.children) { transformError(concatProperty(error, child), result); } } // initializing an empty to evaluate the // length of flattened constraints. let flatConstraints: string[] = []; // if the error has constraints, then extract them. if (error.constraints) { flatConstraints = extractConstraints(error.constraints); } // if and only if there's constraints, assign them. if (flatConstraints.length) { result[error.property] = flatConstraints; } }; const formatErrors = (input: object[]): Result => { const result: Result = {}; for (const error of input) { transformError(error as Error, result); } return result; }; ``` See? `formatErrors` function is the starting point of our algorithm. We iterate through all the errors we get as the input and calls the `transformError` with the `result` instance to hold the flattened records. ## Time complexity The analysis of the time complexity is straightforward. `transformError` is a depth-first traversal of the error tree: it visits each node exactly once, and the only per-node work is extracting that node's own constraints (`extractConstraints` just iterates the constraint entries once). There is no non-trivial recurrence — every node and every constraint is touched a constant number of times. $$ \large{O(N + C)} $$ Where $N$ is the total number of nodes — every error object and every nested child across the tree — and $C$ is the total number of constraints across all of them. If you treat each node's constraint set as bounded, this collapses to the linear $O(N)$. Well, that's it folks! Thanks for reading. --- # Good Git commit messages > Uncover key strategies for crafting effective, clear Git commit messages. July 24, 2022 · 5 min read · https://yasint.dev/good-git-commit-messages/ Tags: git, engineering --- Hey there 👋 When using `git`, it's tempting to commit all your changes at once with a vague message like "fixed stuff" or "updates". But here's the thing: your future self (and your teammates) will thank you for taking a few extra seconds to write clear, meaningful commit messages. ## Why commit messages matter The Git history is the complete record of all changes made to your repository. It's not just a log — it's a story of why decisions were made, what problems were solved, and how the codebase evolved. . To get this output, run the `git log` command. For more, see [git-log official documentation](https://git-scm.com/docs/git-log).") Good commit messages help you: - **Understand changes quickly** — Know exactly what a commit does without reading the code - **Debug faster** — Find when and why a bug was introduced - **Review efficiently** — Make code reviews smoother and more meaningful - **Revert safely** — Undo specific changes without affecting unrelated work ## Keep commits small Small, focused commits are easier to understand, review, and revert if needed. Instead of one massive commit with 20 file changes and a message saying "various fixes", break it into logical chunks: - ✅ "Fix null pointer exception in user authentication" - ✅ "Add validation for email input field" - ✅ "Update dependencies to latest versions" Each commit should represent one logical change. If you can't describe your commit in a single sentence, it's probably doing too much. ## The anatomy of a good commit message Structure your commit message like an email with a subject line and body. ### The subject line Keep it **50 characters or fewer** and make it descriptive.Inherently, MFA handlers require user information to function properly. When we disable JIT for a particular IdP, the system cannot identify and persist information of a user. Thus making the flow ambiguous during multi-factor authentication.
 Well, how can we prevent such scenarios? Asgardeo gives us two choices: - 1. **Enable JIT User provisioning** for the target connection 2. **Conditionally skip MFA for external connections** during the login flow. First choice is obvious. But here's a [sample code I borrowed from the documentation](https://wso2.com/identity-platform/docs/guides/authentication/jit-user-provisioning/#troubleshoot-sign-in-flow-errors) to conditionally skip MFA for federated connections. ```js caption="You should place this snippet in the **Conditional Authentication Section**. First, navigate to Applications > Thrift > Login Flow. And then, Toggle [Conditional Authentication] switch to bring up the script editor. Finally, paste the snippet and update 🎉." // Email & Password authenticator is named as "LOCAL". var localAuthenticator = "LOCAL"; var onLoginRequest = function (context) { executeStep(1, { onSuccess: function (context) { var step = context.steps[1]; // {@code step.idp} is the name that we give // during the connection creation. if (step.idp === localAuthenticator) { executeStep(2); } } }); }; ``` > **Keeping Things Facile** > > Well why do we need MFA for social connections anyway? Right on point! I'm glad you asked. The answer is simply **NO**. We don't have to configure MFA to social connections[^2][^3]. ## Restricted `MyAccount` access Since the login happens in a _pass-through_ mode, these users' profiles aren't logical. Users can still log in to the Thrift app using their accounts, but Asgardeo will not allow them to proceed to the [My Account application](https://wso2.com/identity-platform/docs/guides/user-self-service). All the user attributes derived from the external IdP will also be pass-through to the application (Thrift) without having the capability of editing them _anywhere_. > **Ah, you got me there!** > > Okay, okay, I'll admit it. I lied. When I first wrote this, Asgardeo was still in its baby steps and didn't allow federated connection logins through My Account at all, whether JIT was enabled or disabled. > > That has since changed. My Account is now an application like any other, with its own [`Login Flow` tab](https://wso2.com/identity-platform/docs/guides/user-self-service/configure-self-service-portal/), so you can put Google or GitHub on it. But the **behaviour is very much the same** as I explained above: a federated user who was never provisioned has no local profile for My Account to show or edit. So don't forget that! --- ## What JIT brings to the table? In general, JIT user provisioning aims to reduce your workload and save time when managing federated user identities. Otherwise, you would have to create accounts manually through APIs whenever a new user registers for your application using SSO. JIT user provisioning is Asgardeo's fancy way of handling this complexity. JIT is handy when you integrate social connections tailored for specific use-cases such as **event-based login** and **short lived applications**. Also, in the same way, if we disable JIT, we can shun federated user accounts in the organisation for niche use-cases. --- ## Conclusion Whew! If you made it all the way here, thank you! I admire you. We learned a few things about Asgardeo's JIT user provisioning feature. Let's summarise what we have learned so far. - It's an advanced feature engineered to handle complexities during federated user authentication. - JIT user provisioning happens in the middle of an authentication flow. - Asgardeo allows you to control (enable/disable) this feature. - When enabled, a user profile is created in the local user store to persist information. It creates users on the fly. - When disabled, access to the application happens (Service Provider) in a pass-through mode (without creating user accounts in advance). - When disabled, we need to carefully handle the application's authentication flow and ensure it does not break. And that's it! I hope you've enjoyed this methodical approach on how JIT user provisioning works in Asgardeo, and thanks again for reading! [^1]: Typically, this is addressed as `access_url` of an application. And it is used to navigate through **catalogue** and **discovery flows**. Asgardeo allows you to configure this URL dynamically under `Applications` \> `YOUR_APP` \> `General` settings. [^2]: Social giants like [Google](https://safety.google/authentication), [Facebook](https://www.facebook.com/help/148233965247823), and [GitHub](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa) already have MFA configured in their authentication and authorisation flows. The main reason is that; going through multiple MFA flows in two different identity providers will lead to a poor user experience. Therefore as developers, we can logically reason why we skip MFA for these connections. [^3]: When I'm login in through Google, it usually prompts me a notification on my phone saying (using another authenticated Google app like YouTube, GMail, or Google Photos), **Is this you who are trying to log in?** or **Enter the 2FA code sent to your mobile phone.** Now assume I completed either one of those. If everything goes well, I'm **already validated** by Google. So, it doesn't make sense to initiate another MFA flow in our application if I sign in using Google, right? --- # Monotonic Arrays > Learn how to determine whether an array is either monotonically increasing or decreasing. February 25, 2022 · 7 min read · https://yasint.dev/monotonic-arrays/ Tags: algorithms, javascript --- Let’s say we want to write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic or not. An array is said to be monotonic if its elements, from left to right, are entirely non-increasing or entirely non-decreasing.Well, what’s _non-increasing_ and _non-decreasing_?! It’s confusing at first. So, before we interpret the problem statement, first, we need to understand what we mean by **monotonic** mathematically.
## Monotonicity In mathematics, a monotonic function is a function that is either **non-increasing (decreasing)** or **non-decreasing (increasing)**. If a function is differentiable on an interval, it is monotonic there exactly when its first derivative does not change sign. ## Monotonically increasing A function is called monotonically increasing (also called **increasing** or **non-decreasing**), if for all $x$ and $y$ such that $x \leq y$ one has $f(x) \leq f(y)$, so $f$ preserves the order.  \leq f(y)\$. Note that in a monotonic series, values can be \*\*constant over an interval\*\*.") ## Monotonically decreasing A function is called monotonically decreasing (also called **decreasing** or **non-increasing**) if, whenever $x \leq y$ then $f(x) \geq f(y)$, so it reverses the order.  \geq f(y)$.") ## Strictly increasing and strictly decreasing Say, if the order $\leq$ in the definition of monotonicity is replaced by the strict order $\lt$, one obtains a stronger requirement. A function with this property is called **strictly increasing**, distinguished by a series of continuously increasing sets of values. In the same way, if we _invert_ the symbol ($\geq$ to $\gt$), we get a **strictly decreasing** set of values.  \gt 0 \vee \varDelta f(x) \lt 0$ respectively.") > **Does it have to strictly increase or decrease?** > > The answer is simply **no**. A monotonic series of data can be equal too. So that, **non-increasing** elements aren't necessarily _exclusively decreasing_; they simply don't increase. Similarly, non-decreasing elements aren't necessarily _exclusively increasing_; they merely don't decrease. For example, take a series of arbitrary data points `[ 1, 1, 1, 1, 1 ]` and `[ -1, -1, -1, -1, -1 ]` are entirely valid monotonic series. Hypothetically, if we are to plot this, it would look like the following: -In older versions of Go, we set `$GOROOT` manually. But in newer versions, we don't need to set up the `$GOROOT` variable unless you use different Go versions. If you install Go in a different path, then export the variable `$GOROOT` in your shell's default profile (i.e., `.zshrc`, `.profile`).
You rarely need to care where it points, but when you do, `go env GOROOT` will tell you exactly where the current toolchain lives — no guessing. --- ## What is GOPATH? To explain this, we need to travel back in time. Let's see how things were before Go `1.11`. ## How old GOPATH works When Go was first introduced in 2009, Go authors required you to organize the Go code specifically when working with the `go tool`. A convention to say. Here's some simplified information I borrowed from the docs. - Go programmers typically keep all their Go codes in a single workspace. - A workspace contains many version control repositories (i.e., managed by Git, Bitbucket, etc.). - Each repository contains one or more packages. - Each package consists of Go source files in a single directory. - The path to a package's directory determines its import path. Go authors had this notion called a single workspace directory. It is very different from other programming language environments (i.e., C++) in which the project has a separate workspace and can be multiple workspaces closely tied to version-controlled repositories. But in Golang, a [workspace refers to a directory hierarchy with three directories](https://pkg.go.dev/cmd/go#hdr-GOPATH_environment_variable) at its root. | Directory | Purpose | |:---------:|:-------:| | src | Location of your Go source code i.e., `.go`, `.c`, `.g`, `.s`. The src subdirectory typically contains multiple version control repositories (such as for Git or Mercurial) that track the development of one or more source packages. | | pkg | Location of compiled package code (i.e., `.a`). For example, when you run `go install`, you can use it in your code. | | bin | Location of compiled executable programs built by Go. The go tool builds and installs binaries to this directory. | To give a rough idea of how a workspace looks in practice, here's an example: ```txt hideLineNums hideLang pkg/ darwin_arm64/ golang.org/x/ image/ bmp.a # compiled object example/ stringutil.a # compiled object bin/ hello # command executable outyet # command executable src/ golang.org/x/example/ .git/ # Git repository metadata hello/ hello.go # command source outyet/ main.go # command source main_test.go # test source stringutil/ reverse.go # package source reverse_test.go # test source golang.org/x/image/ .git/ # Git repository metadata bmp/ reader.go # package source writer.go # package source ... (many more repositories and packages omitted) ... ``` Well, now let's take this convention into practice and understand how it was before back then. > **HolUp — Wait a Minute** > > From this point onwards, we will look at how `GOPATH` used to be in earlier versions before `1.11`. And for that, we need to turn off module-aware mode from environment variables. You can check whether you have it enabled or disabled by using the following command. > > ```bash caption="This will show the value of the GO111MODULE variable." > go env GO111MODULE > ``` > > If you don't see the value as `off`, I want you to overwrite the default value by executing `go env -w GO111MODULE=off` to explicitly turn off the module-aware mode. Now we can make sure that we use the semantics before `1.11`. > > By default, Go sets `auto`, `""` (empty string), or `on` as values of `GO111MODULE` depending on the version you are using. > > Sometimes `GO111MODULE` environment variable is a pain in the arse. Gophers rely on this environment variable to change how Go imports packages. As I said, it depends on the version you are using. Go and its module-aware mode semantics change with different Go versions (well, slightly). ### GO111MODULE in Go 1.11 and 1.12 | Value | Behaviour | |-------|-----------| | on | This enforces Go to use modules even if the project is in your `$GOPATH/src`. It strictly requires `go.mod` to work. | | off | This enforces Go to behave the old way (the `$GOPATH way`). Even if you place the project outside `$GOPATH` it will always require the project to be in `$GOPATH/src` (well kinda. I'll explain a way around this). | | auto (default) | This is the default mode. In this mode, Go will behave: - **1)** Similar to `on` when you are outside `$GOPATH/src` and there's a `go.mod` in the current directory or a parent. **2)** Similar to `off` when you are inside the `$GOPATH` even if a `go.mod` is present. | ### GO111MODULE in Go 1.13 | Value | Behaviour | |-------|-----------| | on | Same as `1.11` and `1.12` | | off | Same as `1.11` and `1.12` | | auto (default) | In this mode, Go will behave: - **1)** Behaves like `GO111MODULE=on` anywhere there is a `go.mod` in the current directory or a parent, even inside `GOPATH/src`. This way you can keep all your repositories in your `GOPATH` with Go `1.13`. **2)** Behaves like GO111MODULE=off in the GOPATH if there's no `go.mod`. | ### GO111MODULE in Go 1.14 and 1.15 Has the same semantics as Go version 1.13. ### GO111MODULE in Go 1.16 | Value | Behaviour | |-------|-----------| | on (default) | This will force using Go modules regardless of whether a `go.mod` file is present in the current working directory or a parent directory. | | off | Same as the previous version. | | auto | Same as the previous version. | > In this version, if you see GO111MODULE as `GO111MODULE=""` or `GO111MODULE=` as an empty string or empty value it simply means `GO111MODULE=on`. I found out this via a [issue comment on golang repo](https://github.com/golang/go/issues/42823#issuecomment-735878781). It applies to `1.16` and beyond. In `1.15`, an empty value still meant `auto`. ### GO111MODULE in Go 1.17 Has the same semantics as Go version `1.16`. ### GO111MODULE in Go 1.18 Has the same semantics as Go version `1.17`. However, now `go get` no longer builds or installs packages in `module-aware` mode. `go get` is now dedicated to adjusting dependencies in `go.mod`. Effectively, the `-d` flag is always enabled by default. Please refer the `go cmd` [changelist in the `1.18` release notes for more information](https://go.dev/doc/go1.18#go-get). ### GO111MODULE from Go 1.19 onward Nothing dramatic changed after `1.18`, and honestly that's the headline: modules won. The default has been `on` since `1.16`, and every release since has just leaned into it harder. As of Go `1.26` (the latest as I update this), `GO111MODULE` still exists and you _can_ still flip it to `off`, but that opts you into a legacy code path the Go team actively discourages. In practice, leave it alone. If you ever spot `GO111MODULE=off` in a shell profile or a CI config, it's almost always a leftover from a 2019-era tutorial rather than something anyone meant to keep. So treat everything from here down — the `GO111MODULE=off` walkthrough that follows — as a museum visit. It's worth doing once so the history clicks into place, but it is _not_ how you'd start a Go project today. We'll get to the modern way right after. Now that Go module-aware mode is disabled, the packages we develop and install should be in `$GOPATH` so that the Go build system knows where the imported packages are.Now go tool expects you to keep your project and source files in `GOPATH/src`. And go-tool uses `pkg/` for compiled packages and the `bin/` for executables. This gives you all the necessary files for your development, and go-tool can resolve packages you have imported into your project.
> **Why learn if it's obsolete?** > > Well, I'm glad you asked! Frankly, you don't need to. Especially if you were a Gopher from the very beginning. But if you're just starting out, you might run into slight hiccups here and there from time to time because we still have content that refers to older Go `$GOPATH` behavior. So, it's always better to know the history. Okay, now let's see an example. We can import third-party packages (i.e., libraries written `Go`, `C`, or even `C++`) or our own custom packages to our programs. For example, consider the below application. Let's say we want to create a calculator application. And along the way, publish our calculator operations as a reusable module so that other developers can reuse them. And make the interface and the logic separately in a different package as a driver application. And driver uses a third-party package called [`chalk`](https://github.com/ttacon/chalk) to change the output colors. Sounds easy, right? Let's see how we can do that. ```bash mkdir -p $GOPATH/src/operations # create directory cd $GOPATH/src/operations # navigate to the directory touch operations.go # create package file ``` Open the `operations.go` file in your editor and paste in the following source. ```go name="operations.go" package operations func Add(a int, b int) int { return a + b } func Sub(a int, b int) int { return a - b } ``` Okay, we have already created our reusable operations above. But how can we practically compile and use it in other projects?Well, obviously we need another package to do so. But first, we need to execute `go install` inside the `$GOPATH/src/operations` package to create a compiled binary to use in other applications.
```bash cd $GOPATH/src/operations && go install ``` If you navigate to `$GOPATH/pkg`, you will see that `operations.a` compiled binary file will be generated in `$GOPATH/pkg/${GOOS}_${GOARCH}` directory. ```txt hideLang hideLineNums ├── bin ├── pkg │ └── darwin_arm64 │ └── operations.a └── src └── operations └── operations.go 5 directories, 2 files ``` Now that we have a binary file, we can actually go ahead and create a new application package called `calcapp`[^1]. [^1]: Usually you don't have to worry about things happening inside `/pkg` directory. It's entirely handled by `go tool`. On a high-level note, know that Go uses it to keep compiled package objects (the build cache lives elsewhere, run `go env GOCACHE` to see where). ```bash mkdir -p $GOPATH/src/calcapp # create directory cd $GOPATH/src/calcapp # navigate to application directory touch main.go # create driver main file ``` Remember that we want the third-party library called chalk to format our output. So let's go ahead and install that too. ```bash caption="Before Go 1.22, 'go get github.com/ttacon/chalk' did this in one step. In GOPATH mode it's gone now, so we clone and install by hand." git clone https://github.com/ttacon/chalk $GOPATH/src/github.com/ttacon/chalk && go install github.com/ttacon/chalk ``` There is quite a bit happening in the background. First, without Go `1.11` modules enabled, the package we fetch should be in `$GOPATH` so that the Go build system knows where the imported packages are. ```txt hideLang hideLineNums ├── bin ├── pkg │ └── darwin_arm64 │ ├── github.com │ │ └── ttacon │ │ └── chalk.a │ └── operations.a └── src ├── calcapp │ └── main.go ├── github.com │ └── ttacon │ └── chalk │ ├── LICENSE │ ├── README.md │ ├── chalk.go │ ├── chalk_test.go │ ├── doc.go │ ├── examples │ │ └── main.go │ └── img │ └── chalk_example.png └── operations └── operations.go 13 directories, 11 files ```First, chalk's source sits under `$GOPATH/src` in a `domain/org/package` manner, which is where we cloned it and where `go get` used to put it on its own. And `go install` builds the package and places its compiled binary in `$GOPATH/pkg/${GOOS}_${GOARCH}` in the same way as we talked about.
Now we can start writing our driver application. ```go name="main.go" package main "fmt" "github.com/ttacon/chalk" "operations" ) func main() { log(fmt.Sprintf("Add: %d", operations.Add(2, 2))) log(fmt.Sprintf("Subtract: %d", operations.Sub(4, 2))) } func log(message string) { fmt.Println( chalk.Green, message, chalk.ResetColor, ) } ``` Now we can run the driver application by executing `go run main.go` and see the output. ```bash hideLineNums hideLang $ go run main.go Add: 4 Subtract: 2 ``` Now, if you execute `go install` and check `/bin`, you can see that the executable is put. Navigate to `$GOPATH/src/calcapp` and execute the following. ```txt hideLang hideLineNums $ go install && tree $GOPATH /Users/yasin/go ├── bin │ └── calcapp ├── pkg │ └── darwin_arm64 │ ├── github.com │ │ └── ttacon │ │ └── chalk.a │ └── operations.a └── src ├── calcapp │ └── main.go ├── github.com │ └── ttacon │ └── chalk │ ├── LICENSE │ ├── README.md │ ├── chalk.go │ ├── chalk_test.go │ ├── doc.go │ ├── examples │ │ └── main.go │ └── img │ └── chalk_example.png └── operations └── operations.go 13 directories, 12 files $ ./calcapp # Works because I have added $GOPATH/bin to $PATH Add: 4 Subtract: 2 ``` With this, we explored all subdirectories `src/`, `pkg/`, and `bin/` in the root workspace directory. Well, that's not it. We have a couple of more things left to learn about the old `$GOPATH`. ### Can we place our project outside $GOPATH? When I started learning `Go` back in 2017, I didn't put my go files in `$GOPATH`. My dumbass didn't refer the docs properly. But it turns out, it strangely compiled the code, and it worked for one main package. Even when `GO111MODULE` is disabled or in older versions of Go, we can place our projects outside the go path. This is what I mean: #### Here's a working example I'm implementing a project named `myproject`, with a **package main** and including two files `main.go` and `some_functions.go` as follows: ```bash mkdir -p $HOME/Desktop/myproject cd $HOME/Desktop/myproject touch main.go some_functions.go ``` ```go name="some_functions.go" package main func Test1() { fmt.Printf("hello ") } func Test2() { fmt.Printf("world!\n") } ``` ```go name="main.go" package main func main() { Test1() Test2() } ``` And run it like this: ```txt hideLineNums hideLang $ cd $HOME/Desktop/myproject && go run . hello world! ``` And voilà! Surprisingly, the program runs, even when the project is outside `$GOPATH`. Actually, all projects must be in `$GOPATH` is due to sub-packages. In the above example, we only had the main package. So, it makes sense why it worked. And one main package is not the case, so it is not confined by this limitation. But when you add another package to the project, things get a bit fussy. #### Here's a problematic example ```bash mkdir -p $HOME/Desktop/myproject2 cd $HOME/Desktop/myproject2 && touch main.go mkdir functions && cd functions && touch some_functions.go ``` ```go name="some_functions.go" package functions func Test1() { fmt.Printf("hello ") } func Test2() { fmt.Printf("world!\n") } ``` ```go name="main.go" caption="Go is unable to resolve the package by its relative path or package name." package main // import "functions" // ❌ Big nope. func main() { functions.Test1() functions.Test2() } ``` Without the Go module feature enabled, we cannot specify our `functions/` package in the `main` package, so we cannot find out which should be in the import statement "function" location and cannot build this project. The only way to make it work without Go modules was to move the project into `$GOPATH/src` like so: ```txt hideLineNums hideLang $ tree $GOPATH /Users/yasin/go ├── bin │ ...( executables ) ... ├── pkg │ ...( compiled objects ) ... └── src ├── myproject2 │ ├── functions │ │ └── some_functions.go │ └── main.go | ...( more packages ) ... 15 directories, 14 files ``` ```go name="main.go" obscure="1,2,4,5,6,7,8" caption="When you move the project inside GOPATH/src go is able to resolve the package by its relative path." package main func main() { functions.Test1() functions.Test2() } ``` This was a strictly opinionated approach back in the day, and every Gopher had to follow this convention and maintain their source like this back in the day. Conceptually, this allowed Gophers to link any go code at any instant of time without ambiguity. Well seems pretty _reasonable_, isn't it? But, **NO!**. ### Well, what's the problem then? The above `$GOPATH` approach worked well for a cohesive, more extensive monorepos that doesn't rely on third-party packages[^2]. [^2]: Google has a bunch of monorepos like this.Imagine you have **semantic versioning** in third-party packages and including your own. So with time, it will get hairy real quick. Without any _versioning_ for the packages, it led to all this pain of managing different tags in the source.
Because of this, Go authors decided to introduce the `GO111MODULE` environment variable to handle it. Before Go `1.11`, authors didn't consider shipping the go tool with a package manager. Instead, we used `go get` to fetch all the sources by using their repository import path and placing them in `$GOPATH/src`. Since there was no package manager or any versioning, the `master` branch would represent a stable version of the package.When Google released Go `1.11`, they said: This release adds preliminary support for a new concept called ["modules," an alternative to `GOPATH` with integrated support for versioning and package distribution](https://go.dev/blog/go1.11). Go `1.11` was released on August 24, 2018.
> **Gotcha** > > You might see references to Go Modules as `vgo`. Basically, it means the same thing. And it implies `Versioned Go`. Instead of using the `$GOPATH` for storing a single git checkout of every package, Go Modules stores tagged versions with `go.mod` keeping track of each package's version. However, the go command still uses `$GOPATH/pkg/mod` as the download directory for modules. To make Google's saying correct, the Go module does not entirely replace `$GOPATH`. The `go tool` uses it for package distribution and versioning. The main goal of go modules is to distribute modules in a much more streamlined way. And now we are no longer confined to `GOPATH`. So, placing sources under `src/` folder is ineffective and is not the best practice when you have module-aware mode enabled. The interaction between the _GOPATH behavior_ and the _Go Modules behavior_ has become one of Go's most significant turning points. Finally, now we can learn how it works in practice. ## How GOPATH + GO111MODULE works Now it's time to see how `GOPATH` works with Go Modules. I'll give you a similar example we tried above and modify it to cover the things I mention below. - How to import locally created modules into a project. - How to use remote modules installed via `go get`. - How to use module sub-packages. > **Switch to Go Modules** > > From this point onwards, we are using the modern approach. We are going to turn on `GO111MODULE` from environment variables. > > ```bash > go env -w GO111MODULE=on > ``` > > Also, to increase the clarity of the tutorial, I will be cleaning up my `$GOPATH` and previous examples from my workspace. > > ```bash caption="Use this command wisely. Don't run this if you have any other projects in your $GOPATH." > sudo rm -rf ~/Desktop/myproject $GOPATH/* && cd $GOPATH && mkdir -p src pkg bin > ``` Go ahead and create a workspace anywhere[^3]. First, let's start off with the `operations` package. [^3]: Of course outside `$GOPATH`. ```bash DIR="$HOME/Desktop/go_workspace" # My root workspace mkdir -p $DIR/operations && cd $DIR/operations # Create package directory. go mod init yasint.dev/operations # Module path must match the import. touch $DIR/operations/operations.go # Create the source file. ``` Paste the following source in `operations.go`. ```go name="operations.go" package operations func Add(a int, b int) int { return a + b } func Sub(a int, b int) int { return a - b } ``` Then, let's write the driver application `calcapp`. ```bash caption="Note that we create a subpackage named calcapp/formatters." mkdir -p $DIR/calcapp $DIR/calcapp/formatters # Create package directory. cd $DIR/calcapp && go mod init calcapp # Initialize go module. touch $DIR/calcapp/formatters/formatters.go $DIR/calcapp/main.go # Create source files. ``` Also, for the driver application, we need a third-party package called `chalk`. ```bash caption="Remember, since go 1.18, go get only manages dependencies in go.mod. That's exactly what we want here." go get github.com/ttacon/chalk # Adds chalk to go.mod and go.sum. ``` Paste the following source in `formatters.go`. ```go name="formatters.go" package formatters "fmt" "github.com/ttacon/chalk" ) func Red(message string) { fmt.Println( chalk.Red, message, chalk.ResetColor, ) } func Green(message string) { fmt.Println( chalk.Green, message, chalk.ResetColor, ) } ``` Now notice that we have a custom local package called `operations` — and notice we initialized it as `yasint.dev/operations`, so its module path matches how we'll import it. (If you init a module as plain `operations` but import it as `yasint.dev/operations`, Go won't resolve it — the module path and the import path have to agree.) We need to import that package into our `calcapp` to make it work. So what do we do? To point to the local version of a dependency in Go rather than the one over the web, we use the `replace` keyword within the `go.mod` file. The `replace` line goes above your `require` statements, like so: ```text hideLang name="calcapp/go.mod" module calcapp go 1.26 // Can be github.com/yourname/operations replace yasint.dev/operations => ../operations // 💡 The actual semantic version hash will be different in yours. require github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31 require yasint.dev/operations v0.0.0 ``` And now, when you compile `calcapp` module using `go install`, it will use your local code rather than resolve a non-existing web dependency. > **Replace Directive** > > According to the docs, when using `replace`, you need to [make sure that the code you're pointing to also has a `go.mod` file](https://go.dev/ref/mod#go-mod-file-replace). If not, initialize a module using `go mod init`. We can safely paste the following source in `main.go`. ```go name="main.go" package main "calcapp/formatters" "flag" "fmt" "yasint.dev/operations" ) func main() { isSubtraction := flag.Bool("sub", false, "subtraction operation") aValue := flag.Int("a", 0, "a value") bValue := flag.Int("b", 0, "b value") flag.Parse() if *isSubtraction { formatters.Red( fmt.Sprintf( "Subtraction: %d", operations.Sub(*aValue, *bValue), ), ) } else { formatters.Green( fmt.Sprintf( "Addition: %d", operations.Add(*aValue, *bValue), ), ) } } ``` Did you notice? We can directly import our package by a path like `calcapp/formatters` and even reference local modules effortlessly! How cool is that? Go mod is more intelligent than this. It can even recursively resolve multiple nested sub-packages. ```bash caption="Install the program and run it!" cd ~/Desktop/go_workspace/calcapp go mod tidy # Sync go.mod now that the sources import chalk go install calcapp -a 10 -b 10 # => Addition: 20 calcapp -sub -a 10 -b 5 # => Subtraction: 5 ``` --- ## A more modern take: `go.work` That `replace` dance we just did to wire up a local `operations` module? Go `1.18` gave us a cleaner tool for exactly that: [workspace mode](https://go.dev/ref/mod#workspaces). Instead of hand-editing each `go.mod` with a `replace` directive (and praying you don't accidentally commit it), you drop a single `go.work` file at the root of your workspace: ```bash caption="One file at the workspace root — no per-module replace directives." cd ~/Desktop/go_workspace go work init ./operations ./calcapp ``` Now `calcapp` resolves `operations` straight from your local checkout — no `replace` lines, no fuss — and you keep `go.work` out of version control so it never leaks into anyone else's build. It's the spiritual successor to the old `$GOPATH` workspace: one directory holding several modules you're hacking on together. Except this time nothing is forced to live in a magic folder, and versioning still works the moment you push. Funny how the word "workspace" came all the way back around. ## Conclusion Now we know with Go module-aware mode enabled, Go projects are no longer confined to `$GOPATH`. Meaning Go never restricts the structure or the location of Go projects. Go module alleviates versioning and module resolution constraints elegantly. I hope now you have a better understanding of `$GOPATH` and `$GOROOT`. Thanks for reading! Until next time! --- ## Appendix ### macOS installation (Apple Silicon) We can use [`homebrew`](https://brew.sh/) to install `golang`. It will take care which binaries should be installed for different cpu architectures. #### Install Golang ```bash caption="This command will install golang via homebrew. It might take a few minutes depending on your network connection's speed." brew install golang ``` #### Check installation path Once you installed, brew has a command that you can check where it exactly installed. By executing `brew info golang` you will get a similar output like the following. ```txt hideLineNums hideLang highlight="4" caption="Highlighted line is the installation path." go: stable 1.26.3 (bottled), HEAD Open source programming language to build simple/reliable/efficient software https://go.dev/ /opt/homebrew/Cellar/go/1.26.3 (10,825 files, 564.3MB) * ... ``` #### Verify `go` Check whether the `go` command is working properly to verify you have it in the path. ```bash go version # Outputs => go version go1.26.3 darwin/arm64 ``` > **Tip 💡:** Execute `command -v go` to check the command's path. #### Scrumptious bits Usually when you install a package via brew, it will place the binaries in `/opt/homebrew/Cellar/`. Then after every folder under that is symlinked to `/opt/homebrew/opt` and, the `go` command will be automatically symlinked via `/opt/homebrew/bin`. > In Apple Silicon based macs we have to append the `/opt/homebrew/bin` to your `$PATH` variable to work everything correctly ([Kurt B, Stackoverflow](https://stackoverflow.com/a/65505326/7842206)). ### Other installations Well, for other systems [official Golang installation guide](https://go.dev/doc/install) is far more than enough. --- # Two summation > Probably the most common interview question you'll ever see. Let's solve it. November 21, 2021 · 15 min read · https://yasint.dev/two-summation/ Tags: algorithms --- We want to write a function that takes a non-empty array of distinct integers and an integer representing a target sum. If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If no two numbers sum up to the target sum, the process should return an empty array. > **Intended Audience** > > This article teaches you how to approach and solve the two summation challenge. Therefore, you should be familiar with some basic understanding of programming constructs. And also, we'd be covering the _time_ and _space_ complexity of this algorithm. --- ## First Approach My first approach would be to go through the array of integers in a brute force manner. Suppose we have an array of numbers `[ 1, 2, 3 ]`. We need to figure out all the _two-element combinations_ it can have. If we think about it, we would probably end up doing something like this: , (1,3), (2,3) \ \\}$") Conceptually in this approach, we try to achieve a reducing set of _combinations_ for two numbers and do some calculation with it. If we can align this approach as a solution to our challenge statement, we can write a brute force algorithm like the following: - An **outer loop** which goes through each of element until $n-1$ - An **inner loop** which starts at $x+1$ and goes until the last element - A **condition** to check the summation > **Program Input** — Say we have an array `[ -1, 5, -4, 8, 7, 1, 3, 11 ]` and a target sum `14`. Now let's transform above steps into a pseudocode. ```javascript function solve(array, targetSum) { for (let x = 0; x < array.length - 1; x++) { for (let y = x + 1; y < array.length; y++) { if (array[x] + array[y] === targetSum) { return [array[x], array[y]]; } } } return []; } solve([-1, 5, -4, 8, 7, 1, 3, 11], 14) // [3, 11] ``` If we were to execute this algorithm, what are the different combinations we go through? Let's write down the iterations and their respective combinations manually. | Iteration | Checked Combinations | |:---------:|:--------------------------------------------------------:| | 1 | (-1,5), (-1,-4), (-1,8), (-1,7), (-1,1), (-1,3), (-1,11) | | 2 | (5,-4), (5,8), (5,7), (5,1), (5,3), (5,11) | | 3 | (-4,8), (-4,7), (-4,1), (-4,3), (-4,11) | | 4 | (8,7), (8,1), (8,3), (8,11) | | 5 | (7,1), (7,3), (7,11) | | 6 | (1,3), (1,11) | | 7 | (3,11) | Did you see that? In worst-case scenario we had to evaluate $28$ pairs and in the $7$th iteration we found our matching number pair $(3, 11)$. However, it's not the same always. It will change based on the _indices_ and therefore combinations will be lesser if we break out of the loop after a successful match. > **Combinations** > > In mathematics, a combination is **a selection of items from a collection where the order of the selection does not matter**. > > What we just did is very much similar to [enumerative combinatorics](https://en.wikipedia.org/wiki/Enumerative_combinatorics). You can see that our approach is awfully inefficient in doing that. There are [techniques](https://en.wikipedia.org/wiki/Combinatorial_number_system) that one could use to optimize combination problems. But simply for our first approach, it is _not needed at all_. Instead, I'm leaving this here because this is just one way we could think of the problem. > > If you are interested in learning combinatorics, you can refer to Sal's [explanation](https://www.khanacademy.org/math/statistics-probability/counting-permutations-and-combinations) on Khan Academy. If you're super serious about it, I'd recommend you read [Concrete Mathematics](https://www-cs-faculty.stanford.edu/~knuth/gkp.html) and [Enumerative Combinatorics](https://math.mit.edu/~rstan/ec/) books to solidify your knowledge in it. Now let's do a quick analysis of our first solution. ### Problem Analysis While this works pretty well for smaller arrays, it **won't scale** nicely for larger arrays. The algorithm we just wrote is pretty slow. **Time Complexity** — So, to reiterate, we have an outer loop that goes through the $\text{length}(\text{array}) - 1$ and an inner loop that goes until $\text{length}(\text{array})$ to check the combination of two numbers. This means we check $\frac{n(n-1)}{2}$ pairs, which still grows like $n^2$. $$ \large{{n \choose 2} = \sum_{x = 0}^{n - 2} \ \sum_{y = x+1}^{n - 1} 1 = \frac{n(n-1)}{2}} $$In worst-case scenario, we do ${n \choose 2}$[^1] iterations just to check whether we have a matching pair.
[^1]: Binomial derived from the combinations formula $\frac{n!}{r! \left ( n-r \right )!}$ — we can say that $n$ is the number of elements we have to check, and we have to choose $r$ of them without any order to check the summation. This algorithm has a polynomial time complexity where it grows proportionally to the square of the input size $n$. Unfortunately our algorithm takes $O(n^2)$ time to complete. **Space Complexity** — We only use two `for` loops which involves constant variables as indexes $x$ and $y$. And also, we don't use any extra space. So, our algorithm's space complexity will always be $O(1)$. We know that first approach is bad but can we improve the algorithm and make it a bit faster? What happens if we first _sort_ the array? --- ## Second Approach There's a second way of solving this problem. And it's _slightly_ better than the first one. Initially, in the challenge statement, I didn't mention whether the array is sorted or not. So, what if we sort the array first in ascending order and then figure out a way to solve this? > **Program Input** — Say we are given a new array `[ -4, 13, 1, 3, 5, 6, -1, 11 ]` and a target sum of `10`. Let's use these inputs for our second approach. ### First Operation First, we have to sort the array in ascending order[^2]. In order for the algorithm to work this must be done and then only we can continue. [^2]: You can do it either way. We can sort in **descending** or in **ascending** order. But we have to make sure we swap the _comparing indexes_ along with the _conditions_. But for now let's stick to ascending order to make things simpler.  ### Second Operation Then we can allocate two pointers from _left_ and _right_ to walk through the elements $n - 1$ times and operate on these two numbers.  This way we can solve the problem more optimally instead of using _two for loops_. With a reasonable sorting algorithm like _mergesort_ (or _quicksort_ on average) we could sort the array in $n \ \log(n)$ time. But remember we still have to walk through our $n - 1$ times which is equivalent to $O(n)$. ### Third Operation (doing the summation) So far, now we know the array must be sorted first, and we need two pointers to compare. The core logic of this approach is to drive algorithm's state using three predicates. We need to check whether the sum of $A + B$: 1. Is it **equal** to target sum? 2. Is it **less** than target sum? 3. Is it **greater** than target sum? Let's try to write down the algorithm. Remember that, up to this point, we assume that we have already sorted the array and allocated the two pointers. Now it is time to evaluate the above conditions against each pair in every $n$th iteration. Our loop starts from $x = 0$ and $y = 7$. At this point our $x$'s element is $-4$ and $y$'s element is $13$ (see figure 4). If we add up those two numbers together, we get a total of $9$ which is _less_ than our target sum $10$. In this case **we move the $x$ pointer to the right side**. Basically, incrementing $x$'s index by $1$. That way we can guarantee that in next iteration we would always get a sum $> 9$.  — first iteration") Alright, in the last iteration we moved $x$ by $1$ and now we are at $x = 1$ and $y = 7$ (see figure 5). Once again, if we sum up $-1$ and $13$ we get a total of $12$. Now, this is _larger_ than our expected target sum. In this case **we move the $y$ pointer to left side**. Saying that we want to decrement our $y$ pointer by $1$.  — second iteration") Got the point? We do this iteratively until matching the target sum or until $x$ and $y$ meets together at the same index.  — third iteration") Well, would you look at that? We reduced the number of iterations we have to go through! We have accomplished significant progress in making this algorithm a bit faster. Now that we found our number pair, we can finally return the result and halt the algorithm. Let's write the JavaScript code for this algorithm now. ```javascript function solve(array, targetSum) { const sorted = array.toSorted((a, b) => a - b); let x = 0; let y = sorted.length - 1; while (x < y) { if (sorted[x] + sorted[y] === targetSum) { return [sorted[x], sorted[y]]; } else if (sorted[x] + sorted[y] < targetSum) { x++; } else { y--; } } return []; } ``` While this approach is slightly better than the first, we are back to square one. Why? Well, it's the same reason as before; it does not scale well enough for larger arrays. Let me show you the problem. ### Problem Analysis First, we need to understand the cost of sorting things. [Since ES2019 the spec requires `Array.prototype.sort()` to be stable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort), and V8 [uses TimSort](https://v8.dev/blog/array-sort), a mergesort variant. So let's assume mergesort. It is guaranteed that mergesort runs in $O(n \ \log(n))$ time using $O(n)$ space. And since we only used one `while` loop to drive the state of $x$ and $y$ pointers, we get $O(n \ \log(n)) + O(n)$ which is equivalent to $O(n \ \log(n))$ in total time[^3] and $O(n)$ for space. [^3]: Remember, in _time_ and _space_ complexity analysis we always pick the **dominant** term.  website by [Eric Rowell](https://github.com/ericdrowell)") The algorithm we wrote runs in linearithmic time which tells us its complexity grows proportionally to the array input size with a logarithmic factor. What can we do about it? Can we solve it in linear time? --- ## Hash Set Approach Up until now, all the approaches we have taken is not very optimal from a time standpoint. Fortunately, there's one other way of solving this problem in a much cooler way. You might have thought about this already from the previous approach. But first, let's list down the things we already know: - We know what our target sum is (let it be $z$). - We already know one of our addends[^4] (let it be $x$). [^4]: What I'm referring to is the current element while walking through the array. So, basically we have two variables at hand before even doing any operations. So, we could write an equation like $x + y = z$ to represent it (where $y$ is unknown). Where we can _isolate the unknown_ variable. Say for example, $(x + y) = z$ $\iff$ $y = (z - x)$ > **Inverse Operations** > > To isolate a variable, we cancel out (or undo) operations on the same side of the equation as the variable of interest while maintaining the equality of the equation. > > This can be done by performing inverse operations on the terms that need to be removed so that the variable of interest is isolated. Subtraction cancels out addition, and vice versa, and multiplication cancels out division, and vice versa. Now we can find the unknown variable $y$ without any combinations or two pointers. The only caveat is that we need a way to memorize this calculated value as we go through the array. ### Solution Using some extra space is okay as long as its complexity grows in a reasonable size. Now what do you think? For our solution should we use a _hashmap_? What about a _set_? You'd see a lot of examples of two summation problem's linear-time approach in the internet uses a hashmap auxiliary space implementation. But we really do not need key-value pairs for our solution. Instead, simply we can use a set of numbers to track the inversion results. ### Formal Proof $$ R_i = \{ S - A_j \mid j < i \} $$ $$ A_i \in R_i \iff \exists j < i : A_j + A_i = S $$Before we look at index $i$, $R$ holds the inverse of every element we've already seen, so $A_i \in R$ exactly when some earlier element pairs with it.
### Elaboration We need a loop $\sum_{i=0}^{n - 1}$ that goes through each element of the array starting from index $0$. We need to calculate the inverse set within the loop[^5] so, we create an empty set $R = \emptyset$ and then for each element we calculate $y = z - A_x$[^6] and now we can place a predicate that checks $A_x$ existence in inverse set $R$ like $P(x): (A_x \in R)$ then return $\{ A_x, y \}$ if $P(x)$ is true. Otherwise, $\neg P(x)$ we union our inverse set with the calculated $y$ value where $R \gets R \ \cup \{ y \}$ and we keep on looping until $n - 1$. [^5]: We could also pre-compute the inverse set before the loop, but then an element can match its own inverse (say $5$ with a target of $10$), so we'd have to skip the case where $y = A_x$. Building it as we go avoids that for free. [^6]: $x \in A$ > **Switching to New Inputs** — For this approach let's use the array `[ -7, -5, -3, -1, 0, 1, 3, 5, 7 ]` and the target sum `-5`.  As illustrated, in the first iteration we start off with an empty set named $R$. Initially our loop starts from index $0$ where $i$ is the index variable. In the first iteration we don't have any elements. So, therefore we immediately add the calculated value $2 = -5 - (-7)$ to the set $R$ and move on to the next element.  In the second iteration, first we check whether element at index $1$ is an element of $R$. We can see that $-5 \notin R$ so, we add our inverse calculation $0 = -5 - (-5)$ to set $R$ and continue.  In the third iteration, again we check whether element at index $2$ is an element of $R$. We can see that $-3 \notin R$ so, we do our inverse calculation $-2 = -5 - (-3)$ and add it to set $R$ and continue.  Fourth iteration already! Again we check whether element at index $3$ is an element of $R$. We can see that $-1 \notin R$ so, we do our inverse calculation $-4 = -5 - (-1)$ and add it to set $R$ and continue.  We are in the fifth iteration! And would you look at that! We just found $0$ in our set $R$. This means our inverse got a match! Now we can return these two elements like $\{ A_x, -5 - A_x \}$ where $A_x$ is $0$. Woohoo now we have an idea on how it works, let's write the pseudocode. ```javascript function solve(array, targetSum) { const records = new Set(); for (let x = 0; x < array.length; x++) { let y = targetSum - array[x]; if (records.has(array[x])) { return [array[x], y]; } records.add(y); } return []; } ``` ### Time & Space Complexity In this approach we trade memory for lookups: a set gives us average constant-time membership checks. And we were able to solve it in $O(n)$ expected time and $O(n)$ space complexity. This is the optimal way of solving this problem. --- ## Summary Overall, I think even though two summation is a very easy challenge, we can learn a lot from it. How simple algebraic equations can help to solve complex problems more elegantly. Until next time. Thanks for reading!