Given an integer $n$ and set of triplets of distinct integers $$S \subseteq \{(i, j, k) \mid 1\le i,j,k \le n, i \neq j, j \neq k, i \neq k\},$$ find an algorithm which either finds a permutation $\pi$ of the set $\{1, 2, \dots, n\}$ such that $$(i,j,k) \in S \implies (\pi(j)<\pi(i)<\pi(k)) ~\lor~ (\pi(i)<\pi(k)<\pi(j))$$ or correctly determines that no such permutation exists. Less formally, we want to reorder the numbers 1 through $n$; each triple $(i,j,k)$ in $S$ indicates that $i$ must appear before $k$ in the new order, but $j$ must not appear between $i$ and $k$.
Example 1
Suppose $n=5$ and $S = \{(1,2,3), (2,3,4)\}$. Then
$\pi = (5, 4, 3, 2, 1)$ is not a valid permutation, because $(1, 2, 3)\in S$, but $\pi(1) > \pi(3)$.
$\pi = (1, 2, 4, 5, 3)$ is not a valid permutation, because $(1, 2, 3) \in S$ but $\pi(1) < \pi(3) < \pi(5)$.
$(2, 4, 1, 3, 5)$ is a valid permutation.
Example 2
If $n=5$ and $S = \{(1, 2, 3), (2, 1, 3)\}$, there is no valid permutation. Similarly, there is no valid permutation if $n=5$ and $S = \{(1,2,3), (3,4,5), (2,5,3), (2,1,4)\}$ (I think; may have made a mistake here).
Bonus: What properties of $S$ determine whether a feasible solution exists?